2024-04-29 15:24:34 -07:00

226 lines
9.8 KiB
C#

using Adaptation.Eaf.Management.ConfigurationData.CellAutomation;
using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration;
using Adaptation.Shared;
using Adaptation.Shared.Duplicator;
using Adaptation.Shared.Methods;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading;
namespace Adaptation.FileHandlers.Archive;
public class FileRead : Shared.FileRead, IFileRead
{
#nullable enable
private readonly Timer _Timer;
private static PropertyInfo? _PropertyInfo;
private static NetworkStream? _NetworkStream;
public FileRead(ISMTP smtp, Dictionary<string, string> fileParameter, string cellInstanceName, int? connectionCount, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList<ModelObjectParameterDefinition> modelObjectParameters, string equipmentDictionaryName, Dictionary<string, List<long>> dummyRuns, Dictionary<long, List<string>> staticRuns, bool useCyclicalForDescription, bool isEAFHosted) :
base(new Description(), false, smtp, fileParameter, cellInstanceName, connectionCount, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, dummyRuns, staticRuns, useCyclicalForDescription, isEAFHosted: connectionCount is null)
{
if (_FileConnectorConfiguration.FileScanningIntervalInSeconds is null)
throw new NullReferenceException(nameof(_FileConnectorConfiguration.FileScanningIntervalInSeconds));
_MinFileLength = 10;
_NetworkStream = null;
_Logistics = new(this);
_NullData = string.Empty;
if (_FileParameter is null)
throw new Exception(cellInstanceConnectionName);
if (_ModelObjectParameterDefinitions is null)
throw new Exception(cellInstanceConnectionName);
if (_IsDuplicator)
throw new Exception(cellInstanceConnectionName);
// https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server
TcpListener tcpListener = new(IPAddress.Parse("127.0.0.1"), 8087);
tcpListener.Start();
_ = tcpListener.BeginAcceptTcpClient(OnAccept, tcpListener);
Type type = typeof(NetworkStream);
PropertyInfo? propertyInfo = type.GetProperty("Socket", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty);
if (propertyInfo is null)
throw new NotSupportedException();
_PropertyInfo = propertyInfo;
_Timer = new Timer(Callback, null, Timeout.Infinite, Timeout.Infinite);
if (Debugger.IsAttached || fileConnectorConfiguration.PreProcessingMode == FileConnectorConfiguration.PreProcessingModeEnum.Process)
Callback(null);
else
{
TimeSpan timeSpan = new(DateTime.Now.AddSeconds(_FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks);
_ = _Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite);
}
}
void IFileRead.Move(Tuple<string, Test[], JsonElement[], List<FileInfo>> extractResults, Exception exception) => Move(extractResults);
void IFileRead.WaitForThread() => WaitForThread(thread: null, threadExceptions: null);
string IFileRead.GetEventDescription()
{
string result = _Description.GetEventDescription();
return result;
}
List<string> IFileRead.GetHeaderNames()
{
List<string> results = _Description.GetHeaderNames();
return results;
}
string[] IFileRead.Move(Tuple<string, Test[], JsonElement[], List<FileInfo>> extractResults, string to, string from, string resolvedFileLocation, Exception exception)
{
string[] results = Move(extractResults, to, from, resolvedFileLocation, exception);
return results;
}
JsonProperty[] IFileRead.GetDefault()
{
JsonProperty[] results = _Description.GetDefault(this, _Logistics);
return results;
}
Dictionary<string, string> IFileRead.GetDisplayNamesJsonElement()
{
Dictionary<string, string> results = _Description.GetDisplayNamesJsonElement(this);
return results;
}
List<IDescription> IFileRead.GetDescriptions(IFileRead fileRead, List<Test> tests, IProcessData processData)
{
List<IDescription> results = _Description.GetDescriptions(fileRead, _Logistics, tests, processData);
return results;
}
Tuple<string, Test[], JsonElement[], List<FileInfo>> IFileRead.GetExtractResult(string reportFullPath, string eventName) => throw new Exception(string.Concat("See ", nameof(Callback)));
Tuple<string, Test[], JsonElement[], List<FileInfo>> IFileRead.ReExtract() => throw new Exception(string.Concat("See ", nameof(Callback)));
private static void Archive(FileConnectorConfiguration fileConnectorConfiguration, Calendar calendar, DateTime dateTime, string fileName, string fullFileName)
{
string weekOfYear = $"{dateTime:yyyy}_Week_{calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday):00}";
string archiveDirectory = Path.Combine(fileConnectorConfiguration.TargetFileLocation, "Archive", weekOfYear);
if (!Directory.Exists(archiveDirectory))
_ = Directory.CreateDirectory(archiveDirectory);
string to = Path.Combine(archiveDirectory, fileName);
File.Move(fullFileName, to);
}
internal static void Notify(FileConnectorConfiguration fileConnectorConfiguration, Calendar calendar, DateTime dateTime, string fileName, string fullFileName, string json)
{
if (_NetworkStream is not null)
{
if (!_NetworkStream.CanWrite)
{
TcpListener tcpListener = new(IPAddress.Parse("127.0.0.1"), 8087);
tcpListener.Start();
_ = tcpListener.BeginAcceptTcpClient(OnAccept, tcpListener);
}
else
{
if (_PropertyInfo is null)
throw new NullReferenceException(nameof(_PropertyInfo));
if (_PropertyInfo.GetValue(_NetworkStream) is not Socket socket)
throw new NotSupportedException();
if (!socket.Connected)
{
TcpListener tcpListener = new(IPAddress.Parse("127.0.0.1"), 8087);
tcpListener.Start();
_ = tcpListener.BeginAcceptTcpClient(OnAccept, tcpListener);
}
else
{
BinaryWriter binaryWriter = new(_NetworkStream);
binaryWriter.Write(json);
binaryWriter.Flush();
binaryWriter.Dispose();
Archive(fileConnectorConfiguration, calendar, dateTime, fileName, fullFileName);
}
}
}
}
private static void NetworkStreamDataAvailable(NetworkStream networkStream)
{
int length;
string read;
byte[] bytes = new byte[1024];
StringBuilder stringBuilder = new();
do
{
length = networkStream.Read(bytes, 0, bytes.Length);
read = Encoding.ASCII.GetString(bytes, 0, length);
foreach (char item in read)
{
if (item is '\0')
continue;
_ = stringBuilder.Append(item);
}
}
while (networkStream.DataAvailable);
if (stringBuilder.Length > 0)
throw new NotImplementedException();
}
private static void Callback()
{
if (_NetworkStream is not null && _NetworkStream.CanRead)
{
if (_PropertyInfo is null)
throw new NullReferenceException(nameof(_PropertyInfo));
if (_PropertyInfo.GetValue(_NetworkStream) is not Socket socket)
throw new NotSupportedException();
if (socket.Connected && _NetworkStream.DataAvailable)
NetworkStreamDataAvailable(_NetworkStream);
}
}
private void Callback(object? state)
{
if (_FileConnectorConfiguration.FileScanningIntervalInSeconds is null)
throw new NullReferenceException(nameof(_FileConnectorConfiguration.FileScanningIntervalInSeconds));
try
{
Callback();
}
catch (Exception exception)
{
string subject = string.Concat("Exception:", _CellInstanceConnectionName);
string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace);
try
{ _SMTP.SendHighPriorityEmailMessage(subject, body); }
catch (Exception) { }
}
try
{
TimeSpan timeSpan = new(DateTime.Now.AddSeconds(_FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks);
_ = _Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite);
}
catch (Exception exception)
{
string subject = string.Concat("Exception:", _CellInstanceConnectionName);
string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace);
try
{ _SMTP.SendHighPriorityEmailMessage(subject, body); }
catch (Exception) { }
}
}
private static void OnAccept(IAsyncResult asyncResult)
{
if (asyncResult.AsyncState is TcpListener tcpListener)
{
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(asyncResult);
_NetworkStream = tcpClient.GetStream();
}
}
}