Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to use new server API #344

Merged
merged 2 commits into from Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion source/BulkCrapUninstaller/BulkCrapUninstaller.csproj
Expand Up @@ -116,6 +116,11 @@
<AutoGen>True</AutoGen>
<DependentUpon>Localisable.resx</DependentUpon>
</Compile>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Update="Properties\Settings.Designer.cs">
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<AutoGen>True</AutoGen>
Expand Down Expand Up @@ -190,13 +195,16 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualBasic" Version="10.3.0" />
<PackageReference Include="MySql.Data" Version="8.0.24" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Localisable.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Localisable.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Import Project="..\HelperTools\HelperTools.projitems" Label="Shared" />
<PropertyGroup />
Expand Down
3 changes: 1 addition & 2 deletions source/BulkCrapUninstaller/Forms/Windows/MainWindow.cs
Expand Up @@ -163,8 +163,7 @@ public MainWindow()
_setMan.Selected.Settings.AdvancedSimulate = Program.EnableDebug;

// Tracking
UsageManager.DataSender = new DatabaseStatSender(Program.DbConnectionString,
Resources.DbCommandStats, _setMan.Selected.Settings.MiscUserId);
UsageManager.DataSender = new DatabaseStatSender(Settings.Default.MiscUserId);

// Misc
filterEditor1.ComparisonMethodChanged += SearchCriteriaChanged;
Expand Down
11 changes: 6 additions & 5 deletions source/BulkCrapUninstaller/Functions/Ratings/RatingEntry.cs
Expand Up @@ -14,14 +14,15 @@ public override int GetHashCode()
{
unchecked
{
return (AverageRating.GetHashCode()*397) ^ MyRating.GetHashCode();
return (AverageRating.GetHashCode() * 397) ^ MyRating.GetHashCode();
}
}

public string ApplicationName { get; set; }
public int? AverageRating { get; set; }
public int? MyRating { get; set; }
public bool IsEmpty => ApplicationName == null && !AverageRating.HasValue && !MyRating.HasValue;
public bool IsEmpty => ApplicationName == null && !HasValue;
public bool HasValue => AverageRating.HasValue || MyRating.HasValue;
public static RatingEntry Empty { get; } = default(RatingEntry);

public static RatingEntry NotAvailable { get; } = new RatingEntry
Expand All @@ -39,14 +40,14 @@ public bool Equals(RatingEntry other)
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is RatingEntry && Equals((RatingEntry) obj);
return obj is RatingEntry && Equals((RatingEntry)obj);
}

public static UninstallerRating ToRating(int value)
{
if (value <= ((int) UninstallerRating.Bad + (int) UninstallerRating.Neutral)/2)
if (value <= ((int)UninstallerRating.Bad + (int)UninstallerRating.Neutral) / 2)
return UninstallerRating.Bad;
if (value >= ((int) UninstallerRating.Good + (int) UninstallerRating.Neutral)/2)
if (value >= ((int)UninstallerRating.Good + (int)UninstallerRating.Neutral) / 2)
return UninstallerRating.Good;

return UninstallerRating.Neutral;
Expand Down
Expand Up @@ -6,7 +6,6 @@
using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
Expand All @@ -23,11 +22,8 @@ namespace BulkCrapUninstaller.Functions.Ratings
{
internal class RatingManagerWrapper : IDisposable
{
private static readonly string RatingCacheFilename =
Path.Combine(Program.AssemblyLocation.FullName, "RatingCashe.xml");
private readonly UninstallerRatingManager _ratingManager = new(Settings.Default.MiscUserId);

private readonly UninstallerRatingManager _ratingManager
= new UninstallerRatingManager(WindowsTools.GetUniqueUserId());

private readonly SettingBinder<Settings> _settings = Settings.Default.SettingBinder;

Expand Down Expand Up @@ -55,7 +51,7 @@ public void ProcessGatheredRatings()
}
try
{
_ratingManager.SerializeCache(RatingCacheFilename);
_ratingManager.SerializeCache(Program.AssemblyLocation);
}
catch
{
Expand Down Expand Up @@ -89,16 +85,16 @@ public void InitializeRatingColumn(OLVColumn olvColumnRating, ObjectListView uni

if (!_settings.Settings.MiscUserRatings
|| string.IsNullOrEmpty(model?.RatingId)
|| _ratingManager.RatingCount <= 0)
|| _ratingManager.RemoteRatingCount <= 0)
return Localisable.NotAvailable;

var rating = _ratingManager.GetRating(model.RatingId);

if (rating.IsEmpty || (!rating.AverageRating.HasValue && !rating.MyRating.HasValue))
if (rating.MyRating.HasValue)
return string.Format("Your rating: {0}", RatingEntry.ToRating(rating.MyRating.Value));
else if (rating.AverageRating.HasValue)
return string.Format("Average rating: {0}", RatingEntry.ToRating(rating.AverageRating.Value));
else
return CommonStrings.Unknown;

return (rating.MyRating.HasValue ? "Your rating:" : "Average rating:") + " " +
RatingEntry.ToRating(rating.MyRating ?? (int) rating.AverageRating);
};

uninstallerObjectListView.CellClick += (x, y) =>
Expand All @@ -109,7 +105,7 @@ public void InitializeRatingColumn(OLVColumn olvColumnRating, ObjectListView uni
if (y.Model is not ApplicationUninstallerEntry model)
return;

RateEntries(new[] {model}, uninstallerObjectListView.PointToScreen(y.Location));
RateEntries(new[] { model }, uninstallerObjectListView.PointToScreen(y.Location));
};
}

Expand Down Expand Up @@ -149,7 +145,7 @@ public void InitializeRatings()
{
try
{
_ratingManager.DeserializeCache(RatingCacheFilename);
_ratingManager.DeserializeCache(Program.AssemblyLocation);
}
catch (Exception ex)
{
Expand All @@ -159,7 +155,7 @@ public void InitializeRatings()

// If _ratingManager has no ratings it means that deserialization failed so we need to fetch from db
// Otherwise fetch at most every few hours, unless user manually clears the cache
if (_ratingManager.RatingCount > 0 &&
if (_ratingManager.RemoteRatingCount > 0 &&
(DateTime.Now - _settings.Settings.MiscRatingCacheDate).Duration() < _settings.Settings._CacheUpdateRate)
return;

Expand Down Expand Up @@ -189,7 +185,7 @@ private void FlushRatings()
try
{
_ratingManager.ClearRatings();
UninstallerRatingManager.DeleteCache(RatingCacheFilename);
UninstallerRatingManager.DeleteCache(Program.AssemblyLocation);
}
catch
{
Expand Down
@@ -0,0 +1,79 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.Json;

namespace BulkCrapUninstaller.Functions.Ratings
{
public partial class UninstallerRatingManager
{
internal static class Utils
{
public static T DecompressAndDeserialize<T>(byte[] bytes, JsonSerializerOptions jsonSerializerOptions = null)
{
using (var msInput = new MemoryStream(bytes))
using (var bs = new BrotliStream(msInput, CompressionMode.Decompress))
using (var msOutput = new MemoryStream())
{
bs.CopyTo(msOutput);
msOutput.Seek(0, SeekOrigin.Begin);
var output = msOutput.ToArray();
return JsonSerializer.Deserialize<T>(output, jsonSerializerOptions);
}
}

public static byte[] SerializeAndCompress(object objToJsonserialize)
{
var inputStr = JsonSerializer.Serialize(objToJsonserialize);

var bytes = Encoding.UTF8.GetBytes(inputStr);

using (var outputStream = new MemoryStream())
{
using (var gZipStream = new BrotliStream(outputStream, CompressionLevel.Optimal))
gZipStream.Write(bytes, 0, bytes.Length);

var result = outputStream.ToArray();
//Debug.WriteLine($"Compression result: {bytes.Length} -> {result.Length} ({(result.Length / (double)bytes.Length) * 100:F1}%)");
return result;
}
}


[ThreadStatic] private static System.Security.Cryptography.MD5 _md5;
private static readonly ConcurrentDictionary<string, ulong> _hashCache = new();

public static ulong StableHash(string str)
{
if (str == null) return 0;
if (_hashCache.TryGetValue(str, out var hash))
{
return hash;
}
else
{
if (_md5 == null) _md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(str);
var hashBytes = _md5.ComputeHash(inputBytes);
var stableHash = BitConverter.ToUInt64(hashBytes, 0) ^ BitConverter.ToUInt64(hashBytes, 8);
_hashCache.TryAdd(str, stableHash);
return stableHash;
}
}

public class AverageRatingEntry
{
public int AverageRating { get; set; }
public ulong AppId { get; set; }
}
public class UserRatingEntry
{
public ulong UserId { get; set; }
public int Rating { get; set; }
public ulong AppId { get; set; }
}
}
}
}