Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
qdraw committed Mar 27, 2024
1 parent 6f9125c commit 210caff
Show file tree
Hide file tree
Showing 12 changed files with 205 additions and 69 deletions.
36 changes: 36 additions & 0 deletions starsky/starsky.feature.dependenciescli/DependenciesCliService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Runtime.InteropServices;
using starsky.foundation.database.Data;
using starsky.foundation.database.Helpers;
using starsky.foundation.platform.Helpers;
using starsky.foundation.platform.Interfaces;
using starsky.foundation.platform.Models;
using starsky.foundation.writemeta.Interfaces;

namespace starsky.feature.dependenciescli;

public class DependenciesCliService
{
private IExifToolDownload _exifToolDownload;
private readonly ApplicationDbContext _dbContext;
private IWebLogger _logger;
private AppSettings _appSettings;

public DependenciesCliService(IExifToolDownload exifToolDownload,
ApplicationDbContext dbContext, IWebLogger logger, AppSettings appSettings)
{
_exifToolDownload = exifToolDownload;
_dbContext = dbContext;
_logger = logger;
_appSettings = appSettings;
}

public async Task Run(OSPlatform? currentPlatform = null, Architecture? architecture = null)
{
currentPlatform ??= PlatformParser.GetCurrentOsPlatform();
await RunMigrations.Run(_dbContext, _logger, _appSettings);
await _exifToolDownload.DownloadExifTool(currentPlatform == OSPlatform.Windows);

}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace starsky.feature.dependenciescli.Interfaces;

public interface IDependenciesCliService
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\starsky.foundation.writemeta\starsky.foundation.writemeta.csproj"/>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
Expand All @@ -17,9 +16,9 @@
using starsky.foundation.platform.Models;

[assembly: InternalsVisibleTo("starskytest")]

namespace starsky.feature.packagetelemetry.Services
{

[Service(typeof(IPackageTelemetry), InjectionLifetime = InjectionLifetime.Scoped)]
public class PackageTelemetry : IPackageTelemetry
{
Expand All @@ -29,7 +28,8 @@ public class PackageTelemetry : IPackageTelemetry
private readonly IQuery _query;
private readonly IDeviceIdService _deviceIdService;

public PackageTelemetry(IHttpClientHelper httpClientHelper, AppSettings appSettings, IWebLogger logger, IQuery query, IDeviceIdService deviceIdService)
public PackageTelemetry(IHttpClientHelper httpClientHelper, AppSettings appSettings,
IWebLogger logger, IQuery query, IDeviceIdService deviceIdService)
{
_httpClientHelper = httpClientHelper;
_appSettings = appSettings;
Expand All @@ -38,49 +38,46 @@ public PackageTelemetry(IHttpClientHelper httpClientHelper, AppSettings appSetti
_deviceIdService = deviceIdService;
}

internal const string PackageTelemetryUrl = "qdraw.nl/special/starsky/telemetry/index.php";
internal const string PackageTelemetryUrl = "qdraw.nl/special/starsky/telemetry/v2.php";

internal static object? GetPropValue(object? src, string propName)
{
return src?.GetType().GetProperty(propName)?.GetValue(src, null);
}

internal static OSPlatform? GetCurrentOsPlatform()
{
OSPlatform? currentPlatform = null;
foreach ( var platform in new List<OSPlatform>{OSPlatform.Linux,
OSPlatform.Windows, OSPlatform.OSX,
OSPlatform.FreeBSD}.Where(RuntimeInformation.IsOSPlatform) )
{
currentPlatform = platform;
}

return currentPlatform;
}

internal List<KeyValuePair<string, string>> GetSystemData(OSPlatform? currentPlatform = null, string? deviceId = null)
internal List<KeyValuePair<string, string>> GetSystemData(
OSPlatform? currentPlatform = null, string? deviceId = null)
{
currentPlatform ??= GetCurrentOsPlatform();
currentPlatform ??= PlatformParser.GetCurrentOsPlatform();

var dockerContainer = currentPlatform == OSPlatform.Linux &&
Environment.GetEnvironmentVariable(
"DOTNET_RUNNING_IN_CONTAINER") == "true";
Environment.GetEnvironmentVariable(
"DOTNET_RUNNING_IN_CONTAINER") == "true";

var data = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("UTCTime", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)),
new KeyValuePair<string, string>("UTCTime",
DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)),
new KeyValuePair<string, string>("AppVersion", _appSettings.AppVersion),
new KeyValuePair<string, string>("NetVersion", RuntimeInformation.FrameworkDescription),
new KeyValuePair<string, string>("OSArchitecture", RuntimeInformation.OSArchitecture.ToString()),
new KeyValuePair<string, string>("ProcessArchitecture", RuntimeInformation.ProcessArchitecture.ToString()),
new KeyValuePair<string, string>("OSVersion", Environment.OSVersion.Version.ToString()),
new KeyValuePair<string, string>("OSDescriptionLong", RuntimeInformation.OSDescription.Replace(";", " ")),
new KeyValuePair<string, string>("NetVersion",
RuntimeInformation.FrameworkDescription),
new KeyValuePair<string, string>("OSArchitecture",
RuntimeInformation.OSArchitecture.ToString()),
new KeyValuePair<string, string>("ProcessArchitecture",
RuntimeInformation.ProcessArchitecture.ToString()),
new KeyValuePair<string, string>("OSVersion",
Environment.OSVersion.Version.ToString()),
new KeyValuePair<string, string>("OSDescriptionLong",
RuntimeInformation.OSDescription.Replace(";", " ")),
new KeyValuePair<string, string>("OSPlatform", currentPlatform.ToString()!),
new KeyValuePair<string, string>("DockerContainer", dockerContainer.ToString()),
new KeyValuePair<string, string>("CurrentCulture", CultureInfo.CurrentCulture.ThreeLetterISOLanguageName),
new KeyValuePair<string, string>("AspNetCoreEnvironment", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Not set"),
new KeyValuePair<string, string>("CurrentCulture",
CultureInfo.CurrentCulture.ThreeLetterISOLanguageName),
new KeyValuePair<string, string>("AspNetCoreEnvironment",
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Not set"),
new KeyValuePair<string, string>("WebsiteName", GetEncryptedSiteName()),
new KeyValuePair<string, string>("DeviceId", deviceId ?? "Not set"),
new KeyValuePair<string, string>("RuntimeIdentifier", RuntimeInformation.RuntimeIdentifier),
};
return data;
}
Expand All @@ -89,11 +86,14 @@ private static string GetEncryptedSiteName()
{
var siteName =
Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME");
return string.IsNullOrEmpty(siteName) ? "Not set" : Sha256.ComputeSha256(siteName); // used in Azure web apps
return string.IsNullOrEmpty(siteName)
? "Not set"
: Sha256.ComputeSha256(siteName); // used in Azure web apps
}


internal async Task<List<KeyValuePair<string, string>>> AddDatabaseData(List<KeyValuePair<string, string>> data)
internal async Task<List<KeyValuePair<string, string>>> AddDatabaseData(
List<KeyValuePair<string, string>> data)
{
var fileIndexItemTotalCount = -1;
var fileIndexItemDirectoryCount = -1;
Expand All @@ -112,22 +112,27 @@ internal async Task<List<KeyValuePair<string, string>>> AddDatabaseData(List<Key

data.AddRange(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("FileIndexItemTotalCount",fileIndexItemTotalCount.ToString()),
new KeyValuePair<string, string>("FileIndexItemDirectoryCount",fileIndexItemDirectoryCount.ToString()),
new KeyValuePair<string, string>("FileIndexItemCount",fileIndexItemCount.ToString())
new KeyValuePair<string, string>("FileIndexItemTotalCount",
fileIndexItemTotalCount.ToString()),
new KeyValuePair<string, string>("FileIndexItemDirectoryCount",
fileIndexItemDirectoryCount.ToString()),
new KeyValuePair<string, string>("FileIndexItemCount",
fileIndexItemCount.ToString())
});

return data;
}

internal List<KeyValuePair<string, string>> AddAppSettingsData(List<KeyValuePair<string, string>> data)
internal List<KeyValuePair<string, string>> AddAppSettingsData(
List<KeyValuePair<string, string>> data)
{
var type = typeof(AppSettings);
var properties = type.GetProperties();
// ReSharper disable once LoopCanBeConvertedToQuery
foreach ( var property in properties )
{
var someAttribute = Array.Find(Attribute.GetCustomAttributes(property), x => x is PackageTelemetryAttribute);
var someAttribute = Array.Find(Attribute.GetCustomAttributes(property),
x => x is PackageTelemetryAttribute);
if ( someAttribute == null )
{
continue;
Expand All @@ -143,13 +148,16 @@ internal List<KeyValuePair<string, string>> AddAppSettingsData(List<KeyValuePair
}

if ( propValue?.GetType() == typeof(List<string>) ||
propValue?.GetType() == typeof(Dictionary<string, List<AppSettingsPublishProfiles>>) )
propValue?.GetType() ==
typeof(Dictionary<string, List<AppSettingsPublishProfiles>>) )
{
value = ParseContent(propValue);
}

data.Add(new KeyValuePair<string, string>("AppSettings" + property.Name, value ?? "null"));
data.Add(new KeyValuePair<string, string>("AppSettings" + property.Name,
value ?? "null"));
}

return data;
}

Expand All @@ -160,7 +168,8 @@ internal static string ParseContent(object propValue)

private async Task<bool> PostData(HttpContent formUrlEncodedContent)
{
return ( await _httpClientHelper.PostString("https://" + PackageTelemetryUrl, formUrlEncodedContent,
return ( await _httpClientHelper.PostString("https://" + PackageTelemetryUrl,
formUrlEncodedContent,
_appSettings.EnablePackageTelemetryDebug == true) ).Key;
}

Expand All @@ -171,7 +180,7 @@ private async Task<bool> PostData(HttpContent formUrlEncodedContent)
return null;
}

var currentOsPlatform = GetCurrentOsPlatform();
var currentOsPlatform = PlatformParser.GetCurrentOsPlatform();
var deviceId = await _deviceIdService.DeviceId(currentOsPlatform);

var telemetryDataItems = GetSystemData(currentOsPlatform, deviceId);
Expand All @@ -194,4 +203,3 @@ private async Task<bool> PostData(HttpContent formUrlEncodedContent)
}
}
}

4 changes: 3 additions & 1 deletion starsky/starsky.foundation.http/Services/HttpClientHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using starsky.foundation.injection;
using starsky.foundation.platform.Helpers;
using starsky.foundation.platform.Interfaces;
using starsky.foundation.storage.Helpers;
using starsky.foundation.storage.Interfaces;
using starsky.foundation.storage.Storage;

Expand Down Expand Up @@ -100,12 +101,13 @@ public async Task<KeyValuePair<bool, string>> PostString(string sourceHttpUrl,
// // allow whitelist and https only
if ( !_allowedDomains.Contains(sourceUri.Host) || sourceUri.Scheme != "https" ) return
new KeyValuePair<bool, string>(false, string.Empty);

try
{
using ( HttpResponseMessage response = await _httpProvider.PostAsync(sourceHttpUrl, httpContent) )
using ( Stream streamToReadFrom = await response.Content.ReadAsStreamAsync() )
{

var reader = new StreamReader(streamToReadFrom, Encoding.UTF8);
var result = await reader.ReadToEndAsync();
return new KeyValuePair<bool, string>(response.StatusCode == HttpStatusCode.OK, result);
Expand Down
30 changes: 30 additions & 0 deletions starsky/starsky.foundation.platform/Helpers/PlatformParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace starsky.foundation.platform.Helpers;

public static class PlatformParser
{
public static OSPlatform? GetCurrentOsPlatform()
{
OSPlatform? currentPlatform = null;
foreach ( var platform in new List<OSPlatform>
{
OSPlatform.Linux,
OSPlatform.Windows,
OSPlatform.OSX,
OSPlatform.FreeBSD
}.Where(RuntimeInformation.IsOSPlatform) )
{
currentPlatform = platform;
}

return currentPlatform;
}

public static string GetCurrentArchitecture()
{
return RuntimeInformation.RuntimeIdentifier;
}
}
7 changes: 7 additions & 0 deletions starsky/starsky.sln
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "starsky.feature.desktop", "
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "starskydependenciescli", "starskydependenciescli\starskydependenciescli.csproj", "{CDFE2199-CB93-49E4-AF8A-98A3239F1D3F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "starsky.feature.dependenciescli", "starsky.feature.dependenciescli\starsky.feature.dependenciescli.csproj", "{C34BB48B-0C65-4897-80A9-87CB1BDD5F48}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -374,6 +376,10 @@ Global
{CDFE2199-CB93-49E4-AF8A-98A3239F1D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CDFE2199-CB93-49E4-AF8A-98A3239F1D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CDFE2199-CB93-49E4-AF8A-98A3239F1D3F}.Release|Any CPU.Build.0 = Release|Any CPU
{C34BB48B-0C65-4897-80A9-87CB1BDD5F48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C34BB48B-0C65-4897-80A9-87CB1BDD5F48}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C34BB48B-0C65-4897-80A9-87CB1BDD5F48}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C34BB48B-0C65-4897-80A9-87CB1BDD5F48}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -435,5 +441,6 @@ Global
{F2C4C9DE-22A1-4B34-AC1D-0F08353E0742} = {4B9276C3-651E-48D3-B3A7-3F4D74F3D01A}
{B88C2815-D154-4C6D-AE37-2E150AEBF73D} = {4B9276C3-651E-48D3-B3A7-3F4D74F3D01A}
{CDFE2199-CB93-49E4-AF8A-98A3239F1D3F} = {B974FC20-C3EE-4EB0-AF25-F0D8DA2C28D7}
{C34BB48B-0C65-4897-80A9-87CB1BDD5F48} = {4B9276C3-651E-48D3-B3A7-3F4D74F3D01A}
EndGlobalSection
EndGlobal
26 changes: 12 additions & 14 deletions starsky/starskydependenciescli/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using starsky.foundation.database.Data;
using starsky.foundation.database.Helpers;
using starsky.foundation.injection;
using starsky.foundation.platform.Helpers;
using starsky.foundation.platform.Interfaces;
using starsky.foundation.platform.Models;
using starsky.foundation.storage.Interfaces;
using starsky.foundation.webtelemetry.Extensions;
using starsky.foundation.webtelemetry.Helpers;
using starsky.foundation.writemeta.Interfaces;

namespace starskyDependenciesCli
{
Expand All @@ -25,24 +36,11 @@ public static async Task Main(string[] args)
new SetupDatabaseTypes(appSettings, services).BuilderDb();
serviceProvider = services.BuildServiceProvider();

var geoReverseLookup = serviceProvider.GetRequiredService<IGeoReverseLookup>();
var geoLocationWrite = serviceProvider.GetRequiredService<IGeoLocationWrite>();
var geoFileDownload = serviceProvider.GetRequiredService<IGeoFileDownload>();

var selectorStorage = serviceProvider.GetRequiredService<ISelectorStorage>();

var console = serviceProvider.GetRequiredService<IConsole>();
var exifToolDownload = serviceProvider.GetRequiredService<IExifToolDownload>();
var logger = serviceProvider.GetRequiredService<IWebLogger>();

// Migrations before geo-tools (not needed for this specific app, but helps the process)
await RunMigrations.Run(serviceProvider.GetRequiredService<ApplicationDbContext>(),
logger, appSettings);

// Help and other Command Line Tools args are included in the Geo tools
await new GeoCli(geoReverseLookup, geoLocationWrite, selectorStorage,
appSettings, console, geoFileDownload, exifToolDownload, logger)
.CommandLineAsync(args);
exifToolDownload.DownloadExifTool()
}
}
}
11 changes: 11 additions & 0 deletions starsky/starskydependenciescli/default-init-launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"starskydependenciescli": {
"commandName": "Project",
"commandLineArgs": "-h",
"environmentVariables": {
}
}
}
}
Loading

0 comments on commit 210caff

Please sign in to comment.