move to inherited export

This commit is contained in:
Tommy Parnell
2014-10-20 16:19:53 -04:00
parent e05aa936f1
commit ad20fe7229
19 changed files with 307 additions and 234 deletions

View File

@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013 # Visual Studio 2012
VisualStudioVersion = 12.0.30501.0 VisualStudioVersion = 12.0.30501.0
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NOCQ", "src\NOCQ\NOCQ.csproj", "{83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NOCQ", "src\NOCQ\NOCQ.csproj", "{83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}"
@@ -14,6 +14,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{37EF76
.nuget\packages.config = .nuget\packages.config .nuget\packages.config = .nuget\packages.config
EndProjectSection EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NOCQ.EmailPlugin", "src\NOCQ.EmailPlugin\NOCQ.EmailPlugin.csproj", "{8A49052A-7BD4-4F12-898C-AF398DA5BD07}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -24,21 +26,27 @@ Global
{83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}.Debug|Any CPU.Build.0 = Debug|Any CPU {83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}.Release|Any CPU.ActiveCfg = Release|Any CPU {83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}.Release|Any CPU.Build.0 = Release|Any CPU {83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}.Release|Any CPU.Build.0 = Release|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8A49052A-7BD4-4F12-898C-AF398DA5BD07}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A49052A-7BD4-4F12-898C-AF398DA5BD07}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A49052A-7BD4-4F12-898C-AF398DA5BD07}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Release|Any CPU.Build.0 = Release|Any CPU {8A49052A-7BD4-4F12-898C-AF398DA5BD07}.Release|Any CPU.Build.0 = Release|Any CPU
{D9435B3A-C005-49C2-9C0D-B87330B006D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D9435B3A-C005-49C2-9C0D-B87330B006D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D9435B3A-C005-49C2-9C0D-B87330B006D7}.Debug|Any CPU.Build.0 = Debug|Any CPU {D9435B3A-C005-49C2-9C0D-B87330B006D7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D9435B3A-C005-49C2-9C0D-B87330B006D7}.Release|Any CPU.ActiveCfg = Release|Any CPU {D9435B3A-C005-49C2-9C0D-B87330B006D7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D9435B3A-C005-49C2-9C0D-B87330B006D7}.Release|Any CPU.Build.0 = Release|Any CPU {D9435B3A-C005-49C2-9C0D-B87330B006D7}.Release|Any CPU.Build.0 = Release|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(NestedProjects) = preSolution
HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = src\NOCQ.Application\NOCQ.Application.csproj StartupItem = src\NOCQ.Application\NOCQ.Application.csproj
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NDepend) = preSolution GlobalSection(NDepend) = preSolution
Project = ".\NOCQ.ndproj" Project = ".\NOCQ.ndproj"
EndGlobalSection EndGlobalSection

View File

@@ -3,8 +3,6 @@
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}</ProjectGuid> <ProjectGuid>{DF8CD7EA-76FC-4B57-B24A-52C6373A8EDF}</ProjectGuid>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<RootNamespace>NOCQ.Application</RootNamespace> <RootNamespace>NOCQ.Application</RootNamespace>

View File

@@ -1,43 +1,42 @@
using System; using System;
using System.Dynamic;
using NOCQ.Settings;
using NOCQ.Plugins.Email;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using NOCQ.Extensability; using NOCQ.Extensability;
using System.IO; using NOCQ.Settings;
namespace NOCQ.Application namespace NOCQ.Application
{ {
class MainClass class MainClass
{ {
public static void Main (string[] args) public static void Main (string[] args)
{ {
var s = RedisDatabase.GetNextAlert(SettingsParser.Parse(File.ReadAllText(Path.Combine(".","settings.json"))).Redis); //var s = RedisDatabase.GetNextAlert(SettingsParser.Parse(Path.Combine("settings.json").ToString()).Redis);
// process s // process s
var importPlugs = CatalogRepository.GetImportPlugins(); var importPlugs = CatalogRepository.GetImportPlugins();
importPlugs.ToList().ForEach(x => importPlugs.ToList().ForEach(x =>
{ {
Task.Factory.StartNew(x.Value.Run, TaskCreationOptions.LongRunning); //Task.Factory.StartNew(x.Value.Run, TaskCreationOptions.LongRunning);
Console.WriteLine(x.Value.Name); Console.WriteLine(x.Value.Name);
}); });
//RedisDatabase.SaveAlert(, "127.0.0.1", RedisQueues.Output, 6379, 3000); //RedisDatabase.SaveAlert(, "127.0.0.1", RedisQueues.Output, 6379, 3000);
// Parse the settings file // Parse the settings file
var json = System.IO.File.ReadAllText ("settings.json"); var json = File.ReadAllText ("settings.json");
var settings = SettingsParser.Parse (json); var settings = SettingsParser.Parse (json);
// Load the settings for the email plugin // Load the settings for the email plugin
var email = settings.InputPlugins.Single (x => x.Name == "Email"); //var email = settings.InputPlugins.Single (x => x.Name == "Email");
var emailSettings = email.Settings; //var emailSettings = email.Settings;
//.Create and start an email plugin instance //.Create and start an email plugin instance
var emailPlugin = new ImapInput(emailSettings); //var emailPlugin = new ImapInput(emailSettings);
emailPlugin.Execute(null,null); //emailPlugin.Execute(null,null);
Console.ReadKey (); Console.ReadKey ();
/* /*

View File

@@ -0,0 +1,162 @@
//using System;
//using System.Timers;
//using AE.Net.Mail;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text.RegularExpressions;
//using System.ComponentModel.Composition;
//using Newtonsoft.Json.Linq;
//
//
//namespace NOCQ.Plugins.Email
//{
//
// [IDataImportAttr("Email")]
// public class ImapInput: IDataImportHook
// {
// public IEnumerable<Alert> ImportAlerts (DateTime lastRun)
// {
// throw new NotImplementedException ();
// }
//
// public string Name
// {
// get
// {
// {return "IMAP";}
// }
// }
//
// string loginName { get; set; }
// string password { get; set; }
// string server { get; set; }
// string folderPath { get; set; }
// Timer timer { get; set; }
// int port { get; set; }
// bool ssl { get; set; }
// DateTime lastRun { get; set; }
// IEnumerable<ParseRule> parseRules{ get; set; }
//
//
// public ImapInput (dynamic settings)
// {
// // Load settings from the dynamic object
// // TODO get it to be a EmailSettings now
// if (settings["Username"] == null
// || settings["Password"] == null
// || settings["Host"] == null
// || settings["Folder"] == null)
// throw new ArgumentException ("You are missing a required setting.");
//
// if (settings["ParseRules"] != null) {
// var rules = new List<ParseRule> ();
// foreach (JObject rule in settings["ParseRules"]) {
//
// //var r = rule.Children().Value<ParseRule>();
//
// var r = new ParseRule () {
// Name = rule["Name"].ToString(),
// From = rule["From"].ToString(),
// Enabled = rule["Enabled"].ToString().Equals("true") ? true:false,
// Source = rule["Source"].ToString(),
// System = rule["System"].ToString(),
// Service = rule["Service"].ToString(),
// Severity = rule["Severity"].ToString(),
// Data = rule["Data"].ToString()
// };
//
// if (r.Enabled)
// rules.Add (r);
// }
//
// //var rules = settings ["ParseRules"] as List<ParseRule>;
//
// parseRules = (IEnumerable<ParseRule>)rules.Where (x => x.Enabled).ToList ();
// }
//
// loginName = settings["Username"];
// password = settings["Password"];
// server = settings["Host"];
// folderPath = settings["Folder"];
// port = settings["Port"];
// var period = (string) settings ["Frequency"];
//
// // Set up the timer
// timer = new Timer (Double.Parse(period));
// timer.Elapsed += Execute;
// }
//
// private List<Alert> getAlerts()
// {
// var alerts = new List<Alert> ();
//
// using(var imap = new ImapClient(server, loginName, password, ImapClient.AuthMethods.Login, 993, true)) {
// // Find all undeleted messages from today
// // TODO We probably want to check either all and delete or since last run
// var msgs = imap.SearchMessages(
// SearchCondition.Undeleted().And(
// SearchCondition.SentSince(new DateTime(2014, 5, 7))
// ));
//
// foreach (var msg in msgs)
// {
// var realMsg = msg.Value;
//
// // Figure out if any enabled parse rules apply
// var rule = parseRules.Where (x => x.From.Equals (realMsg.From.Address, StringComparison.CurrentCultureIgnoreCase));
// if (rule.Any ())
// {
// var thisRule = rule.First ();
//
// // Email + ParseRule = Alert
// var source = thisRule.Source;
// var sysRegex = new Regex(thisRule.System);
// var servRegex = new Regex(thisRule.Service);
//
// var sysMatch = sysRegex.Match(realMsg.Body);
// var servMatch = servRegex.Match(realMsg.Body);
//
// if (sysMatch.Success && servMatch.Success) {
// Console.WriteLine ("Source: " + source);
// Console.WriteLine("System: " + sysMatch.Value);
// Console.WriteLine ("Service: " + servMatch.Value);
//
// alerts.Add (new Alert () {
// Source = source,
// System = sysMatch.Value,
// Service = servMatch.Value
// });
// }
// }
// }
// }
//
// return alerts;
// }
//
// // Gather alerts from recent emails and throw them at redis
// public void Execute(object sender, ElapsedEventArgs args)
// {
// var alerts = getAlerts ();
//
// foreach (var alert in alerts) {
// //RedisDatabase.SaveAlert (alert);
// }
// }
//
// // Start the timer
// public void Run()
// {
// Console.WriteLine ("Start");
// timer.Enabled = true;
// timer.Start ();
// }
//
// // Stop the timer
// public void Stop()
// {
// Console.WriteLine ("Stop");
// timer.Stop ();
// }
// }
//}

View File

@@ -0,0 +1,12 @@
using System;
namespace NOCQ.EmailPlugin
{
public class MyClass
{
public MyClass ()
{
}
}
}

View File

@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8A49052A-7BD4-4F12-898C-AF398DA5BD07}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>NOCQ.EmailPlugin</RootNamespace>
<AssemblyName>NOCQ.EmailPlugin</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="MyClass.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Email\EmailSettings.cs" />
<Compile Include="Email\ImapInput.cs">
<DependentUpon>..\..\NOCQ\Plugins\Email\EmailSettings.cs</DependentUpon>
</Compile>
<Compile Include="Email\ParseRule.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\NOCQ\NOCQ.csproj">
<Project>{83651B7D-B58F-46B8-BFE2-BCC0A6C92C7A}</Project>
<Name>NOCQ</Name>
</ProjectReference>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,27 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("NOCQ.EmailPlugin")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("tparnell")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>

View File

@@ -10,36 +10,39 @@ namespace NOCQ
{ {
public sealed class RedisDatabase public sealed class RedisDatabase
{ {
private string host { get; set; } public RedisSettings Settings { get; private set;}
private string q { get; set; } public RedisDatabase(RedisSettings settings)
private string port {get;set;}
private int timeout { get; set;}
public RedisDatabase(){}
public static void SaveAlert(Alert alert, RedisSettings setting)
{ {
using (var redis = new RedisClient(setting.Hostname, if (settings == null)
setting.Port, throw new ArgumentNullException ("settings");
setting.Timeout
Settings = settings;
}
public void SaveAlert(Alert alert)
{
using (var redis = new RedisClient(Settings.Hostname,
Settings.Port,
Settings.Timeout
)) ))
{ {
redis.LPush(setting.InputQueue, JsonConvert.SerializeObject(alert)); redis.LPush(Settings.InputQueue, JsonConvert.SerializeObject(alert));
} }
} }
public static Alert GetNextAlert(RedisSettings setting) public Alert GetNextAlert()
{ {
using (var redis = new RedisClient(setting.Hostname, using (var redis = new RedisClient(Settings.Hostname,
setting.Port, Settings.Port,
setting.Timeout Settings.Timeout
)) ))
{ {
var ts = redis.RPop(setting.OutputQueue); var ts = redis.RPop(Settings.OutputQueue);
return JsonConvert.DeserializeObject<Alert>(ts); return JsonConvert.DeserializeObject<Alert>(ts);

View File

@@ -7,7 +7,7 @@ namespace NOCQ
public class DataImports public class DataImports
{ {
[ImportMany(AllowRecomposition = true)] [ImportMany(AllowRecomposition = true)]
IEnumerable<System.Lazy<IDataImportHook,IDataImportMetadata>> DataHooks {get; set;} IEnumerable<System.Lazy<IDataImportHook>> DataHooks {get; set;}
} }
} }

View File

@@ -1,14 +1,15 @@
using System.Collections.Generic;
using System.ComponentModel.Composition; using System.ComponentModel.Composition;
namespace NOCQ namespace NOCQ
{ {
[InheritedExport]
public interface IDataImportHook public interface IDataImportHook
{ {
string Name { get; } string Name { get; }
void Run(); string Description { get; }
void Stop(); string Version {get;}
IEnumerable<Alert> ImportAlerts (System.DateTime lastRun);
} }
} }

View File

@@ -1,22 +0,0 @@
using System;
using System.ComponentModel.Composition;
namespace NOCQ
{
interface IDataImportMetadata
{
string Name {get;set;}
}
[MetadataAttribute]
public class IDataImportAttr : ExportAttribute, IDataImportMetadata
{
public string Name {get;set;}
public IDataImportAttr(string name)
:base(typeof(IDataImportHook))
{
Name = name;
}
}
}

View File

@@ -11,6 +11,7 @@ namespace NOCQ
public string Data {get;set;} public string Data {get;set;}
public string Runbook {get; set;} public string Runbook {get; set;}
public string Severity {get;set;} public string Severity {get;set;}
public Guid Id {get;set;}
} }
} }

View File

@@ -62,13 +62,8 @@
<ItemGroup> <ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Extensability\Catalog.cs" /> <Compile Include="Extensability\Catalog.cs" />
<Compile Include="Plugins\Email\EmailSettings.cs" />
<Compile Include="Imports\IDataImportHook.cs" /> <Compile Include="Imports\IDataImportHook.cs" />
<Compile Include="Imports\DataImports.cs" /> <Compile Include="Imports\DataImports.cs" />
<Compile Include="Plugins\Email\ParseRule.cs" />
<Compile Include="Plugins\Email\ImapInput.cs">
<DependentUpon>EmailSettings.cs</DependentUpon>
</Compile>
<Compile Include="Model\Alert.cs" /> <Compile Include="Model\Alert.cs" />
<Compile Include="DB\RedisQueues.cs"> <Compile Include="DB\RedisQueues.cs">
<DependentUpon>RedisDatabase.cs</DependentUpon> <DependentUpon>RedisDatabase.cs</DependentUpon>
@@ -76,10 +71,8 @@
<Compile Include="Settings\SettingsFIle.cs" /> <Compile Include="Settings\SettingsFIle.cs" />
<Compile Include="Settings\RedisSettings.cs" /> <Compile Include="Settings\RedisSettings.cs" />
<Compile Include="Settings\SettingsParser.cs" /> <Compile Include="Settings\SettingsParser.cs" />
<Compile Include="Settings\PluginSettings.cs" />
<Compile Include="DB\RedisDatabase.cs" /> <Compile Include="DB\RedisDatabase.cs" />
<Compile Include="Extensability\CatalogRepository.cs" /> <Compile Include="Extensability\CatalogRepository.cs" />
<Compile Include="Imports\IDataImportMetadata.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup> <ItemGroup>
@@ -90,7 +83,6 @@
<Folder Include="Imports\" /> <Folder Include="Imports\" />
<Folder Include="DB\" /> <Folder Include="DB\" />
<Folder Include="Plugins\" /> <Folder Include="Plugins\" />
<Folder Include="Plugins\Email\" />
<Folder Include="Model\" /> <Folder Include="Model\" />
<Folder Include="Settings\" /> <Folder Include="Settings\" />
</ItemGroup> </ItemGroup>

View File

@@ -1,157 +0,0 @@
using System;
using System.Timers;
using AE.Net.Mail;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.ComponentModel.Composition;
using Newtonsoft.Json.Linq;
namespace NOCQ.Plugins.Email
{
[IDataImportAttr("Email")]
public class ImapInput: IDataImportHook
{
public string Name
{
get
{
{return "IMAP";}
}
}
string loginName { get; set; }
string password { get; set; }
string server { get; set; }
string folderPath { get; set; }
Timer timer { get; set; }
int port { get; set; }
bool ssl { get; set; }
DateTime lastRun { get; set; }
IEnumerable<ParseRule> parseRules{ get; set; }
public ImapInput (dynamic settings)
{
// Load settings from the dynamic object
// TODO get it to be a EmailSettings now
if (settings["Username"] == null
|| settings["Password"] == null
|| settings["Host"] == null
|| settings["Folder"] == null)
throw new ArgumentException ("You are missing a required setting.");
if (settings["ParseRules"] != null) {
var rules = new List<ParseRule> ();
foreach (JObject rule in settings["ParseRules"]) {
//var r = rule.Children().Value<ParseRule>();
var r = new ParseRule () {
Name = rule["Name"].ToString(),
From = rule["From"].ToString(),
Enabled = rule["Enabled"].ToString().Equals("true") ? true:false,
Source = rule["Source"].ToString(),
System = rule["System"].ToString(),
Service = rule["Service"].ToString(),
Severity = rule["Severity"].ToString(),
Data = rule["Data"].ToString()
};
if (r.Enabled)
rules.Add (r);
}
//var rules = settings ["ParseRules"] as List<ParseRule>;
parseRules = (IEnumerable<ParseRule>)rules.Where (x => x.Enabled).ToList ();
}
loginName = settings["Username"];
password = settings["Password"];
server = settings["Host"];
folderPath = settings["Folder"];
port = settings["Port"];
var period = (string) settings ["Frequency"];
// Set up the timer
timer = new Timer (Double.Parse(period));
timer.Elapsed += Execute;
}
private List<Alert> getAlerts()
{
var alerts = new List<Alert> ();
using(var imap = new ImapClient(server, loginName, password, ImapClient.AuthMethods.Login, 993, true)) {
// Find all undeleted messages from today
// TODO We probably want to check either all and delete or since last run
var msgs = imap.SearchMessages(
SearchCondition.Undeleted().And(
SearchCondition.SentSince(new DateTime(2014, 5, 7))
));
foreach (var msg in msgs)
{
var realMsg = msg.Value;
// Figure out if any enabled parse rules apply
var rule = parseRules.Where (x => x.From.Equals (realMsg.From.Address, StringComparison.CurrentCultureIgnoreCase));
if (rule.Any ())
{
var thisRule = rule.First ();
// Email + ParseRule = Alert
var source = thisRule.Source;
var sysRegex = new Regex(thisRule.System);
var servRegex = new Regex(thisRule.Service);
var sysMatch = sysRegex.Match(realMsg.Body);
var servMatch = servRegex.Match(realMsg.Body);
if (sysMatch.Success && servMatch.Success) {
Console.WriteLine ("Source: " + source);
Console.WriteLine("System: " + sysMatch.Value);
Console.WriteLine ("Service: " + servMatch.Value);
alerts.Add (new Alert () {
Source = source,
System = sysMatch.Value,
Service = servMatch.Value
});
}
}
}
}
return alerts;
}
// Gather alerts from recent emails and throw them at redis
public void Execute(object sender, ElapsedEventArgs args)
{
var alerts = getAlerts ();
foreach (var alert in alerts) {
//RedisDatabase.SaveAlert (alert);
}
}
// Start the timer
public void Run()
{
Console.WriteLine ("Start");
timer.Enabled = true;
timer.Start ();
}
// Stop the timer
public void Stop()
{
Console.WriteLine ("Stop");
timer.Stop ();
}
}
}

View File

@@ -7,7 +7,6 @@ namespace NOCQ.Settings
public class SettingsFile public class SettingsFile
{ {
public RedisSettings Redis { get; set; } public RedisSettings Redis { get; set; }
public IEnumerable<PluginSettings> InputPlugins {get; set; }
} }
} }

View File

@@ -1,11 +1,12 @@
using System; using System;
using System.IO;
namespace NOCQ.Settings namespace NOCQ.Settings
{ {
public class SettingsParser public static class SettingsParser
{ {
public static SettingsFile Parse(string json){ public static SettingsFile Parse(string filePath = "settings.json"){
return Newtonsoft.Json.JsonConvert.DeserializeObject<SettingsFile>(json);
return Newtonsoft.Json.JsonConvert.DeserializeObject<SettingsFile>(File.ReadAllText(filePath));
} }
} }
} }