mirror of
https://github.com/donavon04/MPELicenseAgent.git
synced 2025-01-17 16:40:57 -07:00
327 lines
11 KiB
C#
327 lines
11 KiB
C#
// Decompiled with JetBrains decompiler
|
|
// Type: LicenseTrackerService.Service1
|
|
// Assembly: LicenseTrackerService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
|
|
// MVID: 190801E4-3027-41A4-B03A-CBAE9DAB23BA
|
|
// Assembly location: C:\MPE\MPELicenseTracker\LicenseTrackerService.exe
|
|
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.ServiceProcess;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Timers;
|
|
|
|
#nullable disable
|
|
namespace LicenseTrackerService
|
|
{
|
|
public class Service1 : ServiceBase
|
|
{
|
|
private string homeBaseAddress = "apilicenses.mpe.ca";
|
|
private string apiKey = "&v94gt8ZHFTTTeuT";
|
|
private string[] requestedPrograms = new string[15];
|
|
private Timer pollRateTimer;
|
|
private int pollRate;
|
|
private bool canPhoneHome = false;
|
|
private IContainer components = (IContainer) null;
|
|
|
|
public Service1() => this.InitializeComponent();
|
|
|
|
protected override async void OnStart(string[] args)
|
|
{
|
|
this.WriteToFile("\n*******************************************************\nMPE License Tracker\nMade by: Donavon McDowell\n");
|
|
try
|
|
{
|
|
await this.getHealth();
|
|
if (this.canPhoneHome)
|
|
{
|
|
this.WriteToFile(DateTime.Now.ToString() + " Connected to home base " + this.homeBaseAddress);
|
|
await this.getPollRate();
|
|
await this.getRequestedPrograms();
|
|
await this.getClientPrograms();
|
|
}
|
|
}
|
|
catch (Exception ex1)
|
|
{
|
|
Exception ex = ex1;
|
|
}
|
|
this.pollRateTimer = new Timer();
|
|
this.pollRateTimer.Interval = (double) this.pollRate;
|
|
this.pollRateTimer.Elapsed += new ElapsedEventHandler(this.OnElapsedTime);
|
|
this.pollRateTimer.Start();
|
|
}
|
|
|
|
protected override void OnStop()
|
|
{
|
|
if (this.pollRateTimer == null)
|
|
return;
|
|
this.pollRateTimer.Stop();
|
|
this.pollRateTimer.Dispose();
|
|
}
|
|
|
|
private async void OnElapsedTime(object source, ElapsedEventArgs e)
|
|
{
|
|
await this.getHealth();
|
|
if (!this.canPhoneHome)
|
|
return;
|
|
await this.getRequestedPrograms();
|
|
await this.getPollRate();
|
|
await this.getClientPrograms();
|
|
this.pollRateTimer.Interval = (double) this.pollRate;
|
|
}
|
|
|
|
private async Task getHealth()
|
|
{
|
|
string baseUrl = "https://" + this.homeBaseAddress;
|
|
string endpoint = "/api/healthcheck";
|
|
HttpMethod method = HttpMethod.Get;
|
|
HttpClient httpClient = new HttpClient()
|
|
{
|
|
Timeout = TimeSpan.FromSeconds(4.0)
|
|
};
|
|
try
|
|
{
|
|
HttpResponseMessage response = await httpClient.GetAsync(baseUrl + endpoint);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
string responses = await response.Content.ReadAsStringAsync();
|
|
if (!string.IsNullOrEmpty(responses))
|
|
{
|
|
this.canPhoneHome = true;
|
|
}
|
|
else
|
|
{
|
|
this.canPhoneHome = false;
|
|
this.WriteToFile(DateTime.Now.ToString() + " Disconnected from home base " + this.homeBaseAddress);
|
|
}
|
|
responses = (string) null;
|
|
}
|
|
else
|
|
{
|
|
this.canPhoneHome = false;
|
|
this.WriteToFile(DateTime.Now.ToString() + " Disconnected from home base " + this.homeBaseAddress);
|
|
}
|
|
response = (HttpResponseMessage) null;
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
httpClient = (HttpClient) null;
|
|
}
|
|
catch (TaskCanceledException ex)
|
|
{
|
|
this.canPhoneHome = false;
|
|
this.WriteToFile(DateTime.Now.ToString() + " [Error]: Connection timed out while trying to phone home to " + this.homeBaseAddress);
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
httpClient = (HttpClient) null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.canPhoneHome = false;
|
|
this.WriteToFile(DateTime.Now.ToString() + " [Error]: There was an error in the getHealth() function. " + ex.Message);
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
httpClient = (HttpClient) null;
|
|
}
|
|
}
|
|
|
|
private async Task getRequestedPrograms()
|
|
{
|
|
string baseUrl = "https://" + this.homeBaseAddress;
|
|
string endpoint = "/api/programs";
|
|
HttpMethod method = HttpMethod.Get;
|
|
try
|
|
{
|
|
string responses = await Service1.ApiClient.hitApi(baseUrl, endpoint, method);
|
|
string cleanedResponses = responses.Trim('[', ']');
|
|
string[] responseArray = cleanedResponses.Split(new string[1]
|
|
{
|
|
"\",\""
|
|
}, StringSplitOptions.None);
|
|
responseArray[0] = responseArray[0].Trim('"');
|
|
responseArray[responseArray.Length - 1] = responseArray[responseArray.Length - 1].Trim('"');
|
|
this.requestedPrograms = responseArray;
|
|
responses = (string) null;
|
|
cleanedResponses = (string) null;
|
|
responseArray = (string[]) null;
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.WriteToFile(DateTime.Now.ToString() + " [Error]: There was an error in the getRequestedPrograms() function. " + ex?.ToString());
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
}
|
|
|
|
private async Task getClientPrograms()
|
|
{
|
|
Process[] processes = Process.GetProcesses();
|
|
string[] matchingProcesses = ((IEnumerable<Process>) processes).Select<Process, string>((Func<Process, string>) (p => p.ProcessName)).Where<string>((Func<string, bool>) (pn => ((IEnumerable<string>) this.requestedPrograms).Contains<string>(pn, (IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase))).Distinct<string>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase).ToArray<string>();
|
|
string[] strArray = matchingProcesses;
|
|
for (int index = 0; index < strArray.Length; ++index)
|
|
{
|
|
string processName = strArray[index];
|
|
await this.sendMatchingPrograms(processName);
|
|
processName = (string) null;
|
|
}
|
|
strArray = (string[]) null;
|
|
processes = (Process[]) null;
|
|
matchingProcesses = (string[]) null;
|
|
}
|
|
|
|
private async Task sendMatchingPrograms(string applicationName)
|
|
{
|
|
string currentMachineName = Environment.MachineName;
|
|
string baseUrl = "https://" + this.homeBaseAddress;
|
|
string endpoint = "/api/currentPrograms";
|
|
HttpMethod method = HttpMethod.Post;
|
|
try
|
|
{
|
|
var payload = new
|
|
{
|
|
applicationName = applicationName,
|
|
machineName = currentMachineName,
|
|
apiKey = this.apiKey
|
|
};
|
|
string response = await Service1.ApiClient.hitApi(baseUrl, endpoint, method, (object) payload);
|
|
Console.WriteLine("Response from server: " + response);
|
|
payload = null;
|
|
response = (string) null;
|
|
currentMachineName = (string) null;
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
catch (HttpRequestException ex)
|
|
{
|
|
Console.WriteLine("Network error: " + ex.Message);
|
|
currentMachineName = (string) null;
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
Console.WriteLine("JSON parsing error: " + ex.Message);
|
|
currentMachineName = (string) null;
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine("Error: " + ex.Message);
|
|
currentMachineName = (string) null;
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
}
|
|
|
|
private async Task getPollRate()
|
|
{
|
|
string baseUrl = "https://" + this.homeBaseAddress;
|
|
string endpoint = "/api/pollrate";
|
|
HttpMethod method = HttpMethod.Get;
|
|
try
|
|
{
|
|
string response = await Service1.ApiClient.hitApi(baseUrl, endpoint, method);
|
|
JObject jsonObject = JObject.Parse(response);
|
|
string pollrateString = (string) jsonObject["pollrate"];
|
|
this.pollRate = int.Parse(pollrateString);
|
|
response = (string) null;
|
|
jsonObject = (JObject) null;
|
|
pollrateString = (string) null;
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine(ex.Message);
|
|
baseUrl = (string) null;
|
|
endpoint = (string) null;
|
|
method = (HttpMethod) null;
|
|
}
|
|
}
|
|
|
|
public void WriteToFile(string data)
|
|
{
|
|
string str1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
|
|
if (!Directory.Exists(str1))
|
|
Directory.CreateDirectory(str1);
|
|
string str2 = Path.Combine(str1, "ServiceLog.txt");
|
|
if (File.Exists(str2) && new FileInfo(str2).Length / 1024L > 100L)
|
|
{
|
|
File.Delete(str2);
|
|
using (StreamWriter text = File.CreateText(str2))
|
|
text.WriteLine(data);
|
|
}
|
|
else
|
|
{
|
|
using (StreamWriter streamWriter = File.AppendText(str2))
|
|
streamWriter.WriteLine(data);
|
|
}
|
|
}
|
|
|
|
protected override void Dispose(bool disposing)
|
|
{
|
|
if (disposing && this.components != null)
|
|
this.components.Dispose();
|
|
base.Dispose(disposing);
|
|
}
|
|
|
|
private void InitializeComponent()
|
|
{
|
|
this.components = (IContainer) new System.ComponentModel.Container();
|
|
this.ServiceName = nameof (Service1);
|
|
}
|
|
|
|
public static class ApiClient
|
|
{
|
|
public static async Task<string> hitApi(
|
|
string baseUrl,
|
|
string endpoint,
|
|
HttpMethod method,
|
|
object data = null)
|
|
{
|
|
string str;
|
|
using (HttpClient client = new HttpClient())
|
|
{
|
|
client.BaseAddress = new Uri(baseUrl);
|
|
HttpResponseMessage response;
|
|
if (method == HttpMethod.Get)
|
|
{
|
|
response = await client.GetAsync(endpoint);
|
|
}
|
|
else
|
|
{
|
|
if (!(method == HttpMethod.Post))
|
|
throw new NotSupportedException(string.Format("HTTP method {0} is not supported.", (object) method));
|
|
string jsonData = JsonConvert.SerializeObject(data);
|
|
StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
|
|
response = await client.PostAsync(endpoint, (HttpContent) content);
|
|
jsonData = (string) null;
|
|
content = (StringContent) null;
|
|
}
|
|
response.EnsureSuccessStatusCode();
|
|
str = await response.Content.ReadAsStringAsync();
|
|
}
|
|
return str;
|
|
}
|
|
}
|
|
}
|
|
}
|