[chore] Perform ReSharper cleanup

This commit is contained in:
achiez
2025-11-07 10:35:10 +02:00
parent 8e5fea54cd
commit 982bb4d0c8
77 changed files with 599 additions and 543 deletions
+2 -2
View File
@@ -1,8 +1,8 @@
using AchiesUtilities.Extensions;
using System.Reflection;
using AchiesUtilities.Extensions;
using NebulaAuth.LegacyConverter;
using Newtonsoft.Json;
using SteamLib.Utility.MafileSerialization;
using System.Reflection;
try
{
+3 -3
View File
@@ -1,9 +1,9 @@
using NebulaAuth.Core;
using System;
using System.Windows;
using NebulaAuth.Core;
using NebulaAuth.Model;
using NebulaAuth.Model.Exceptions;
using NebulaAuth.Model.MAAC;
using System;
using System.Windows;
namespace NebulaAuth;
@@ -11,7 +11,7 @@ public class BoolToValueConverter : IValueConverter
if (value is not bool b) return Binding.DoNothing;
if (parameter is Array)
{
var arr = (Array)parameter;
var arr = (Array) parameter;
if (arr.Length == 0) return Binding.DoNothing;
var first = arr.GetValue(0);
var second = arr.Length > 1 ? arr.GetValue(1) : null;
+2 -2
View File
@@ -13,8 +13,8 @@
<converters:ColorToBrushConverter x:Key="ColorToBrushConverter" />
<converters:AnyMafilesToVisibilityConverter x:Key="AnyMafilesToVisibilityConverter" />
<converters:PortableMaClientStatusToColorConverter x:Key="PortableMaClientStatusToColorConverter" />
<converters:BoolToMafileNamingConverter x:Key="BoolToMafileNamingConverter"/>
<converters:BoolToValueConverter x:Key="BoolToValueConverter"/>
<converters:BoolToMafileNamingConverter x:Key="BoolToMafileNamingConverter" />
<converters:BoolToValueConverter x:Key="BoolToValueConverter" />
<converters:NullableToBooleanConverter x:Key="NullableToBooleanConverter" />
<!-- Background converters-->
<background:BackgroundImageVisibleConverter x:Key="BackgroundImageVisibleConverter" />
+19 -19
View File
@@ -13,25 +13,6 @@ namespace NebulaAuth.Core;
public static class DialogsController
{
#region CommonDialogs
public static async Task<bool> ShowConfirmCancelDialog(string? msg = null)
{
var content = msg == null ? new ConfirmCancelDialog() : new ConfirmCancelDialog(msg);
var result = await DialogHost.Show(content);
return result != null && (bool) result;
}
public static async Task<string?> ShowTextFieldDialog(string? title = null, string? msg = null)
{
var content = new TextFieldDialog(title, msg);
var result = await DialogHost.Show(content);
return result as string;
}
#endregion
public static async Task<LoginAgainVM?> ShowLoginAgainDialog(string username, string? currentPassword = null)
{
var vm = new LoginAgainVM
@@ -131,4 +112,23 @@ public static class DialogsController
};
await DialogHost.Show(dialog);
}
#region CommonDialogs
public static async Task<bool> ShowConfirmCancelDialog(string? msg = null)
{
var content = msg == null ? new ConfirmCancelDialog() : new ConfirmCancelDialog(msg);
var result = await DialogHost.Show(content);
return result != null && (bool) result;
}
public static async Task<string?> ShowTextFieldDialog(string? title = null, string? msg = null)
{
var content = new TextFieldDialog(title, msg);
var result = await DialogHost.Show(content);
return result as string;
}
#endregion
}
+5 -3
View File
@@ -1,7 +1,6 @@
using System;
using System.IO;
using AutoUpdaterDotNET;
using NebulaAuth.Model;
namespace NebulaAuth.Core;
@@ -24,9 +23,12 @@ public static class UpdateManager
try
{
var testFile = Path.Combine(Environment.CurrentDirectory, "test.tmp");
using (File.Create(testFile)) { }
using (File.Create(testFile))
{
}
File.Delete(testFile);
return false;
return false;
}
catch (UnauthorizedAccessException)
{
+63 -63
View File
@@ -34,7 +34,7 @@
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="Find"
Executed="FocusSearchBox"/>
Executed="FocusSearchBox" />
</Window.CommandBindings>
<Border Name="DragNDropBorder" Panel.ZIndex="3" Opacity="1" AllowDrop="True"
DragDrop.DragEnter="Rectangle_DragEnter" DragLeave="Rectangle_DragLeave" Drop="Rectangle_Drop">
@@ -86,15 +86,13 @@
Command="{Binding OpenMafileFolderCommand}" />
<MenuItem IsEnabled="False" Header="⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯" Height="15" />
<MenuItem Header="{Tr MainWindow.Menu.File.ProxyManager}"
Command="{Binding OpenProxyManagerCommand}">
</MenuItem>
Command="{Binding OpenProxyManagerCommand}" />
<MenuItem Header="{Tr MainWindow.Menu.File.Settings}"
Command="{Binding OpenSettingsDialogCommand}" />
<MenuItem IsEnabled="False" Header="⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯" Height="15" />
<MenuItem Header="{Tr MainWindow.Menu.File.Other.Title}">
<MenuItem Header="{Tr MainWindow.Menu.File.Other.SetPasswords}"
Command="{Binding DebugCommand}"
/>
Command="{Binding DebugCommand}" />
</MenuItem>
</MenuItem>
</Menu>
@@ -276,8 +274,9 @@
SelectedValue="{Binding SelectedMafile}"
PreviewMouseDown="MafileListBox_OnPreviewMouseDown">
<ListBox.Resources>
<DiscreteObjectKeyFrame x:Key="groupsProxy" Value="{Binding Groups}"/>
<DiscreteObjectKeyFrame x:Key="listBoxProxy" Value="{Binding ElementName=MafileListBox}"/>
<DiscreteObjectKeyFrame x:Key="groupsProxy" Value="{Binding Groups}" />
<DiscreteObjectKeyFrame x:Key="listBoxProxy"
Value="{Binding ElementName=MafileListBox}" />
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem"
@@ -327,72 +326,74 @@
Command="{Binding DataContext.CopyPasswordCommand, RelativeSource={RelativeSource AncestorType=Window}}"
CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}" />
</ListBox.InputBindings>
<FrameworkElement.ContextMenu>
<FrameworkElement.ContextMenu>
<ContextMenu Tag="{Binding Groups}">
<MenuItem InputGestureText="Ctrl+C"
Header="{Tr MainWindow.ContextMenus.Mafile.CopyLogin}"
Command="{Binding CopyLoginCommand}"
CommandParameter="{Binding PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<MenuItem InputGestureText="Ctrl+C"
Header="{Tr MainWindow.ContextMenus.Mafile.CopyLogin}"
Command="{Binding CopyLoginCommand}"
CommandParameter="{Binding PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<MenuItem Header="{Tr MainWindow.ContextMenus.Mafile.CopyPassword}"
Command="{Binding Path=CopyPasswordCommand}"
CommandParameter="{Binding Path=PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
InputGestureText="CTRL+⇧+C"/>
CommandParameter="{Binding Path=PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
InputGestureText="CTRL+⇧+C" />
<MenuItem Header="{Tr MainWindow.ContextMenus.Mafile.CopySteamId}"
Command="{Binding CopySteamIdCommand}"
CommandParameter="{Binding PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<MenuItem InputGestureText="Ctrl+X"
Header="{Tr MainWindow.ContextMenus.Mafile.CopyMafile}"
Command="{Binding CopyMafileCommand}"
CommandParameter="{Binding PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<MenuItem Header="{Tr MainWindow.ContextMenus.Mafile.AddToGroup}"
>
<MenuItem.ItemsSource>
<CompositeCollection>
<MenuItem
Command="{Binding CreateGroupCommand}"
CommandParameter="{Binding Value.SelectedValue, Source={StaticResource listBoxProxy}}">
Command="{Binding CopySteamIdCommand}"
CommandParameter="{Binding PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<MenuItem InputGestureText="Ctrl+X"
Header="{Tr MainWindow.ContextMenus.Mafile.CopyMafile}"
Command="{Binding CopyMafileCommand}"
CommandParameter="{Binding PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<MenuItem Header="{Tr MainWindow.ContextMenus.Mafile.AddToGroup}">
<MenuItem.ItemsSource>
<CompositeCollection>
<MenuItem
Command="{Binding CreateGroupCommand}"
CommandParameter="{Binding Value.SelectedValue, Source={StaticResource listBoxProxy}}">
<MenuItem.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<md:PackIcon Kind="PlusCircle" VerticalAlignment="Center"/>
<TextBlock VerticalAlignment="Center" Margin="5,0,0,0" Grid.Column="1" Text="{Tr MainWindow.ContextMenus.Mafile.CreateGroup}"></TextBlock>
<md:PackIcon Kind="PlusCircle"
VerticalAlignment="Center" />
<TextBlock VerticalAlignment="Center"
Margin="5,0,0,0" Grid.Column="1"
Text="{Tr MainWindow.ContextMenus.Mafile.CreateGroup}" />
</Grid>
</MenuItem.Header>
</MenuItem>
<Separator />
<CollectionContainer Collection="{Binding Value, Source={StaticResource groupsProxy}}" />
<Separator />
<CollectionContainer
Collection="{Binding Value, Source={StaticResource groupsProxy}}" />
</CompositeCollection>
</MenuItem.ItemsSource>
</MenuItem.ItemsSource>
<ItemsControl.ItemContainerStyle>
<Style BasedOn="{StaticResource MaterialDesignMenuItem}"
TargetType="{x:Type MenuItem}">
<Setter Property="Command"
Value="{Binding DataContext.AddToGroupCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<Setter Property="CommandParameter">
<Setter.Value>
<MultiBinding
Converter="{StaticResource MultiCommandParameterConverter}">
<Binding />
<Binding Path="PlacementTarget.SelectedValue"
RelativeSource="{RelativeSource AncestorType=ContextMenu}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
</MenuItem>
<MenuItem Header="{Tr MainWindow.ContextMenus.Mafile.RemoveFromGroup}"
Command="{Binding Path=RemoveGroupCommand}"
CommandParameter="{Binding Path=PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
/>
<ItemsControl.ItemContainerStyle>
<Style BasedOn="{StaticResource MaterialDesignMenuItem}"
TargetType="{x:Type MenuItem}">
<Setter Property="Command"
Value="{Binding DataContext.AddToGroupCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<Setter Property="CommandParameter">
<Setter.Value>
<MultiBinding
Converter="{StaticResource MultiCommandParameterConverter}">
<Binding />
<Binding Path="PlacementTarget.SelectedValue"
RelativeSource="{RelativeSource AncestorType=ContextMenu}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
</MenuItem>
<MenuItem Header="{Tr MainWindow.ContextMenus.Mafile.RemoveFromGroup}"
Command="{Binding Path=RemoveGroupCommand}"
CommandParameter="{Binding Path=PlacementTarget.SelectedValue, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
</ContextMenu>
</FrameworkElement.ContextMenu>
</ContextMenu>
</FrameworkElement.ContextMenu>
</ListBox>
@@ -411,15 +412,15 @@
<Grid Grid.Column="1">
<Border Background="{DynamicResource MaterialDesign.Brush.Card.Background}"
Opacity="{Binding Settings.RightOpacity}"
BorderThickness="1"
BorderThickness="1"
Margin="10,10,15,10" CornerRadius="12" VerticalAlignment="Stretch">
<Border.BorderBrush>
<SolidColorBrush Color="{DynamicResource Base300Color}" Opacity="0.3" />
</Border.BorderBrush>
</Border>
<md:Card Margin="10,10,15,10" Padding="2" UniformCornerRadius="12"
Background="Transparent" >
Background="Transparent">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -448,8 +449,7 @@
Visibility="{Binding SelectedMafile, Converter={StaticResource NullableToVisibilityConverter}}"
Grid.Row="1" Height="4"
Style="{StaticResource MaterialDesignLinearProgressBar}"
MaxTime="30" TimeRemaining="{Binding CodeProgress, Mode=OneWay}"
/>
MaxTime="30" TimeRemaining="{Binding CodeProgress, Mode=OneWay}" />
</Grid>
<Button IsEnabled="{Binding IsMafileSelected}"
FontSize="14"
+5 -5
View File
@@ -70,6 +70,11 @@ public partial class MainWindow
}
}
private void FocusSearchBox(object sender, ExecutedRoutedEventArgs e)
{
SearchField.Focus();
}
#region Dran'n'Drop
private void UIElement_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
@@ -121,9 +126,4 @@ public partial class MainWindow
}
#endregion
private void FocusSearchBox(object sender, ExecutedRoutedEventArgs e)
{
SearchField.Focus();
}
}
+4 -3
View File
@@ -20,16 +20,17 @@ public partial class Mafile : MobileDataExtended
set => SetProperty(ref _linkedClient, value);
}
[JsonIgnore] public string? Filename
[JsonIgnore]
public string? Filename
{
get => _filename;
set => SetProperty(ref _filename, value);
}
[JsonIgnore] private PortableMaClient? _linkedClient;
private string? _filename;
[JsonIgnore] private PortableMaClient? _linkedClient;
public void SetSessionData(MobileSessionData? sessionData)
{
SessionData = sessionData;
+17 -12
View File
@@ -1,12 +1,12 @@
using System;
using NebulaAuth.Model.Entities;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using NebulaAuth.Core;
using NebulaAuth.Model.Entities;
using Newtonsoft.Json;
namespace NebulaAuth.Model.MAAC;
@@ -14,7 +14,9 @@ public static class MAACStorage
{
private static Dictionary<string, StoredClient> Clients { get; set; } = [];
static MAACStorage(){}
static MAACStorage()
{
}
private static void ClientsOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
@@ -26,7 +28,7 @@ public static class MAACStorage
{
foreach (var item in e.NewItems)
{
if (item is Mafile { Filename: not null } mafile)
if (item is Mafile {Filename: not null} mafile)
{
if (mafile.LinkedClient != null)
mafile.LinkedClient.PropertyChanged += LinkedClientOnPropertyChanged;
@@ -44,7 +46,7 @@ public static class MAACStorage
{
foreach (var item in e.OldItems)
{
if (item is Mafile { Filename: not null } mafile)
if (item is Mafile {Filename: not null} mafile)
{
if (mafile.LinkedClient != null)
mafile.LinkedClient.PropertyChanged -= LinkedClientOnPropertyChanged;
@@ -67,6 +69,7 @@ public static class MAACStorage
client.PropertyChanged -= LinkedClientOnPropertyChanged;
return;
}
if (e.PropertyName == nameof(PortableMaClient.AutoConfirmMarket))
{
anyChanges = storedClient.AutoConfirmMarket != client.AutoConfirmMarket;
@@ -77,6 +80,7 @@ public static class MAACStorage
anyChanges = storedClient.AutoConfirmTrades != client.AutoConfirmTrades;
storedClient.AutoConfirmTrades = client.AutoConfirmTrades;
}
if (anyChanges)
Save();
}
@@ -98,7 +102,7 @@ public static class MAACStorage
{
var mafile = Storage.MaFiles.FirstOrDefault(x => x.Filename == fileName);
if (mafile == null) continue;
if(storedClient is {AutoConfirmMarket: false, AutoConfirmTrades: false}) continue;
if (storedClient is {AutoConfirmMarket: false, AutoConfirmTrades: false}) continue;
if (MultiAccountAutoConfirmer.TryAddToConfirm(mafile) && mafile.LinkedClient != null)
{
mafile.LinkedClient.AutoConfirmMarket = storedClient.AutoConfirmMarket;
@@ -107,13 +111,14 @@ public static class MAACStorage
}
}
}
catch(Exception ex)
catch (Exception ex)
{
Shell.Logger.Error(ex, "Failed to load MAAC storage");
SnackbarController.SendSnackbar(LocManager.GetCodeBehindOrDefault("FailedToLoadStorage", "MAAC", "FailedToLoadStorage"));
SnackbarController.SendSnackbar(
LocManager.GetCodeBehindOrDefault("FailedToLoadStorage", "MAAC", "FailedToLoadStorage"));
}
MultiAccountAutoConfirmer.Clients.CollectionChanged += ClientsOnCollectionChanged;
MultiAccountAutoConfirmer.Clients.CollectionChanged += ClientsOnCollectionChanged;
}
public static void NotifyMafilesRenamed(IDictionary<string, string> oldNewNames)
@@ -121,19 +126,19 @@ public static class MAACStorage
var updatedClients = new Dictionary<string, StoredClient>();
foreach (var (oldName, newName) in oldNewNames)
{
if(Clients.Remove(oldName, out var storedClient))
if (Clients.Remove(oldName, out var storedClient))
{
updatedClients[newName] = storedClient;
}
}
Clients = updatedClients;
Save();
}
private class StoredClient
{
{
public bool AutoConfirmMarket { get; set; }
public bool AutoConfirmTrades { get; set; }
}
}
@@ -134,7 +134,6 @@ public static class MultiAccountAutoConfirmer
Clients.Remove(mafile);
mafile.LinkedClient?.Dispose();
mafile.LinkedClient = null;
});
}
@@ -154,6 +153,7 @@ public static class MultiAccountAutoConfirmer
{
dueTime = timerInterval >= 30 ? intervalTimeSpan : TimeSpan.FromSeconds(30);
}
Timer.Change(dueTime, intervalTimeSpan);
}
@@ -1,4 +1,12 @@
using AchiesUtilities.Web.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using AchiesUtilities.Web.Models;
using AchiesUtilities.Web.Proxy;
using CommunityToolkit.Mvvm.ComponentModel;
using NebulaAuth.Core;
@@ -11,14 +19,6 @@ using SteamLib.Exceptions.Authorization;
using SteamLib.SteamMobile.Confirmations;
using SteamLib.Web;
using SteamLibForked.Abstractions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace NebulaAuth.Model.MAAC;
@@ -1,9 +1,8 @@
using NebulaAuth.Model.Entities;
using NebulaAuth.Utility;
using System;
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using NebulaAuth.Model.Entities;
using NebulaAuth.Utility;
namespace NebulaAuth.Model.Mafiles;
@@ -15,8 +14,6 @@ public interface IMafileNamingStrategy
public class MafileNamingStrategy : IMafileNamingStrategy
{
public static MafileNamingStrategy SteamId { get; } = new("{steamid}");
public static MafileNamingStrategy Login { get; } = new("{login}");
public const string DEF_EXTENSION = ".mafile";
public static readonly IDictionary<string, Func<Mafile, string?>> Placeholders =
@@ -28,6 +25,9 @@ public class MafileNamingStrategy : IMafileNamingStrategy
{"{servertime}", GetServerTime}
}.ToFrozenDictionary();
public static MafileNamingStrategy SteamId { get; } = new("{steamid}");
public static MafileNamingStrategy Login { get; } = new("{login}");
public string Pattern { get; }
public bool IncludeExtension { get; }
@@ -47,7 +47,8 @@ public class MafileNamingStrategy : IMafileNamingStrategy
public string GetMafileName(Mafile mafile)
{
if (!CanNameMafile(mafile)) throw new InvalidOperationException($"Cannot name mafile with the current pattern {Pattern}");
if (!CanNameMafile(mafile))
throw new InvalidOperationException($"Cannot name mafile with the current pattern {Pattern}");
return ApplyPatternSubstitution(mafile, Pattern, IncludeExtension);
}
@@ -62,11 +63,27 @@ public class MafileNamingStrategy : IMafileNamingStrategy
result = result.Replace(placeholder.Key, value, StringComparison.OrdinalIgnoreCase);
}
}
return includeExtension ? result + DEF_EXTENSION : result;
}
private static string GetSteamId(Mafile mafile) => mafile.SteamId.Steam64.ToString();
private static string GetLogin(Mafile mafile) => mafile.AccountName;
private static string? GetGroup(Mafile mafile) => mafile.Group;
private static string GetServerTime(Mafile mafile) => mafile.ServerTime.ToString();
private static string GetSteamId(Mafile mafile)
{
return mafile.SteamId.Steam64.ToString();
}
private static string GetLogin(Mafile mafile)
{
return mafile.AccountName;
}
private static string? GetGroup(Mafile mafile)
{
return mafile.Group;
}
private static string GetServerTime(Mafile mafile)
{
return mafile.ServerTime.ToString();
}
}
+2 -1
View File
@@ -47,7 +47,8 @@ public static class ProxyStorage
catch (Exception ex)
{
Shell.Logger.Error(ex, "Error while loading proxies");
SnackbarController.SendSnackbar(LocManager.GetCodeBehindOrDefault("Error when loading proxies", "ProxyStorage", "ErrorWhileLoadingProxies"));
SnackbarController.SendSnackbar(LocManager.GetCodeBehindOrDefault("Error when loading proxies",
"ProxyStorage", "ErrorWhileLoadingProxies"));
SnackbarController.SendSnackbar(ex.Message);
}
}
+2 -1
View File
@@ -41,7 +41,8 @@ public partial class Settings : ObservableObject
}
catch (Exception ex)
{
SnackbarController.SendSnackbar(LocManager.GetCodeBehindOrDefault("Error when loading settings", "Settings", "ErrorWhileLoadingSettings"));
SnackbarController.SendSnackbar(LocManager.GetCodeBehindOrDefault("Error when loading settings", "Settings",
"ErrorWhileLoadingSettings"));
SnackbarController.SendSnackbar(ex.Message);
Instance = new Settings();
}
+3 -3
View File
@@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using System;
using Microsoft.Extensions.Logging;
using NebulaAuth.Model.Exceptions;
using NLog;
using NLog.Extensions.Logging;
using SteamLib.Core;
using SteamLib.SteamMobile;
using System;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace NebulaAuth.Model;
@@ -39,7 +39,7 @@ public static class Shell
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Logger.Fatal((Exception)e.ExceptionObject);
Logger.Fatal((Exception) e.ExceptionObject);
LogManager.Shutdown();
}
}
+26 -18
View File
@@ -1,11 +1,4 @@
using AchiesUtilities.Extensions;
using NebulaAuth.Model.Entities;
using NebulaAuth.Model.Exceptions;
using NebulaAuth.Model.Mafiles;
using SteamLib;
using SteamLib.Exceptions.Authorization;
using SteamLib.SteamMobile;
using System;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -14,8 +7,14 @@ using System.IO.Compression;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Data;
using AchiesUtilities.Extensions;
using NebulaAuth.Model.Entities;
using NebulaAuth.Model.Exceptions;
using NebulaAuth.Model.MAAC;
using NebulaAuth.Model.Mafiles;
using SteamLib;
using SteamLib.Exceptions.Authorization;
using SteamLib.SteamMobile;
namespace NebulaAuth.Model;
@@ -46,7 +45,7 @@ public static class Storage
await Task.Run(() =>
{
return Parallel.ForEachAsync(files,
new ParallelOptions { CancellationToken = token, MaxDegreeOfParallelism = threadCount },
new ParallelOptions {CancellationToken = token, MaxDegreeOfParallelism = threadCount},
async (file, ct) =>
{
try
@@ -105,11 +104,13 @@ public static class Storage
SaveMafile(data);
}
public static Mafile ReadMafile(string path)
{
var str = File.ReadAllText(path);
return NebulaSerializer.Deserialize(str, path);
}
public static async Task<Mafile> ReadMafileAsync(string path)
{
var str = await File.ReadAllTextAsync(path);
@@ -151,6 +152,7 @@ public static class Storage
MaFiles.Add(data);
}
}
public static void UpdateMafile(Mafile data)
{
var path = GetOrCreateMafilePath(data);
@@ -164,6 +166,7 @@ public static class Storage
var str = NebulaSerializer.SerializeMafile(data);
await File.WriteAllTextAsync(Path.GetFullPath(path), str);
}
public static void MoveToRemoved(Mafile data)
{
var sourcePath = GetOrCreateMafilePath(data);
@@ -180,6 +183,7 @@ public static class Storage
File.Delete(sourcePath);
MaFiles.Remove(data);
}
private static string GetOrCreateMafilePath(Mafile data)
{
if (data.Filename != null)
@@ -210,6 +214,7 @@ public static class Storage
var json = NebulaSerializer.SerializeMafile(data, null);
WriteBackup(data.AccountName, json);
}
public static void WriteBackup(string accountName, string data)
{
Directory.CreateDirectory(DIR_BACKUP_MAFILES);
@@ -224,7 +229,7 @@ public static class Storage
var zipPath = Path.Combine(BackupMafilesDirectory, backupFileName);
await using (var zipStream = new FileStream(zipPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, leaveOpen: false);
using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, false);
var files = Directory
.EnumerateFiles(MafilesDirectory, "*.*", SearchOption.TopDirectoryOnly)
.Where(f => Path.GetExtension(f).Equals(".mafile", StringComparison.OrdinalIgnoreCase))
@@ -238,12 +243,12 @@ public static class Storage
await using var entryStream = entry.Open();
await using var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 4096,
useAsync: true);
true);
await fileStream.CopyToAsync(entryStream);
if (counter % 5 == 0)
{
progress?.Report(counter / (double)files.Count);
progress?.Report(counter / (double) files.Count);
await Task.Delay(10);
}
}
@@ -261,17 +266,17 @@ public static class Storage
{
try
{
var targetFileName = CreateMafileFileName(mafile, loginAsFileName);
if (mafile.Filename == targetFileName || mafile.Filename == null)
{
res.Renamed += 1;
continue;
}
var sourceFileName = mafile.Filename;
var fullSourcePath = Path.Combine(MafilesDirectory, sourceFileName);
var fullTargetPath = Path.Combine(MafilesDirectory, targetFileName);
if (!File.Exists(fullSourcePath))
{
Shell.Logger.Warn("Can't rename mafile {old} to {new} because source file not found",
@@ -287,11 +292,11 @@ public static class Storage
res.Conflict += 1;
continue;
}
File.Move(fullSourcePath, fullTargetPath);
dic[sourceFileName] = targetFileName;
res.Renamed += 1;
mafile.Filename = targetFileName;
}
catch (Exception ex)
{
@@ -304,7 +309,10 @@ public static class Storage
MAACStorage.NotifyMafilesRenamed(dic);
return res;
void IncErrors() => res.Errors += 1;
void IncErrors()
{
res.Errors += 1;
}
}
public class MafileRenameResult
+1 -1
View File
@@ -67,7 +67,7 @@
<ItemGroup>
<Folder Include="Theme\Controls\" />
<Folder Include="Theme\Controls\" />
</ItemGroup>
</Project>
+6 -2
View File
@@ -1,3 +1,7 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml"
xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=components/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=viewmodel_005Clinker_005Csteps/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=viewmodel_005Clinker_005Csteps/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
+7 -5
View File
@@ -1,7 +1,8 @@
using NebulaAuth.Core;
using NebulaAuth.Model;
using System;
using System;
using System.Collections.Specialized;
using System.Windows.Forms;
using NebulaAuth.Core;
using NebulaAuth.Model;
namespace NebulaAuth.Utility;
@@ -11,7 +12,7 @@ public class ClipboardHelper
{
try
{
System.Windows.Forms.Clipboard.SetText(text);
Clipboard.SetText(text);
return true;
}
catch (Exception ex)
@@ -27,7 +28,7 @@ public class ClipboardHelper
{
try
{
System.Windows.Forms.Clipboard.SetFileDropList(files);
Clipboard.SetFileDropList(files);
return true;
}
catch (Exception ex)
@@ -35,6 +36,7 @@ public class ClipboardHelper
Shell.Logger.Error(ex);
SnackbarController.SendSnackbar(LocManager.GetCommonOrDefault("Error", "Error"));
}
return false;
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
using System;
using System.IO;
using System.IO;
using System.Linq;
namespace NebulaAuth.Utility;
@@ -41,7 +41,7 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<nebulaAuth:HintBox FontSize="14" x:Name="ConfirmHint" Text="Confirm?" Margin="10"/>
<nebulaAuth:HintBox FontSize="14" x:Name="ConfirmHint" Text="Confirm?" Margin="10" />
<Grid Grid.Row="1" Margin="10,0,10,5">
<Grid.ColumnDefinitions>
<ColumnDefinition />
@@ -56,7 +56,7 @@
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
CommandParameter="{StaticResource True}"
Content="{Tr Common.OK}"
IsDefault="True"/>
IsDefault="True" />
<Button Grid.Column="1"
HorizontalAlignment="Right"
Width="130"
@@ -65,8 +65,7 @@
Style="{StaticResource MaterialDesignOutlinedButton}"
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
CommandParameter="{StaticResource False}"
Content="{Tr Common.Cancel}"
/>
Content="{Tr Common.Cancel}" />
</Grid>
</Grid>
</Grid>
@@ -1,6 +1,5 @@
namespace NebulaAuth.View.Dialogs;
public partial class SetCryptPasswordDialog
{
public SetCryptPasswordDialog()
@@ -40,7 +40,7 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox x:Name="TextField" Margin="10" materialDesign:HintAssist.Hint=""></TextBox>
<TextBox x:Name="TextField" Margin="10" materialDesign:HintAssist.Hint="" />
<Grid Grid.Row="1" Margin="10,0,10,5">
<Grid.ColumnDefinitions>
<ColumnDefinition />
@@ -54,8 +54,7 @@
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
CommandParameter="{Binding Text, ElementName=TextField}"
Content="{Tr Common.OK}"
IsDefault="True"
/>
IsDefault="True" />
<Button Grid.Column="1"
HorizontalAlignment="Right"
Width="130"
@@ -64,8 +63,7 @@
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
IsCancel="True"
CommandParameter="{x:Null}"
Content="{Tr Common.Cancel}"
/>
Content="{Tr Common.Cancel}" />
</Grid>
</Grid>
</Grid>
@@ -2,7 +2,6 @@
namespace NebulaAuth.View.Dialogs;
public partial class TextFieldDialog
{
public TextFieldDialog()
@@ -14,7 +13,7 @@ public partial class TextFieldDialog
{
InitializeComponent();
if(!string.IsNullOrWhiteSpace(title))
if (!string.IsNullOrWhiteSpace(title))
TitleTextBlock.Text = title;
if (!string.IsNullOrEmpty(msg))
@@ -3,7 +3,6 @@ using System.Windows;
namespace NebulaAuth.View.Dialogs;
public partial class WaitLoginDialog
{
private TaskCompletionSource<string> _tcs = new();
-1
View File
@@ -4,7 +4,6 @@ using System.Windows.Controls;
namespace NebulaAuth.View;
public partial class LinksView : UserControl
{
public LinksView()
@@ -2,7 +2,6 @@
namespace NebulaAuth.View;
public partial class MafileMoverView : UserControl
{
public MafileMoverView()
+10 -10
View File
@@ -59,16 +59,16 @@
<Run Text="{Tr ProxyManagerDialog.DefaultProxy, IsDynamic=False}" />
<Run Text="{Binding DefaultProxy.Key, StringFormat='&#x0a;0:', FallbackValue='-', Mode=OneWay}" />
<Run>
<Run.Text>
<MultiBinding Mode="OneWay"
Converter="{StaticResource ProxyDataTextMultiConverter}">
<Binding Path="DefaultProxy.Value" />
<Binding Path="DataContext.DisplayProtocol"
RelativeSource="{RelativeSource AncestorType=UserControl}" />
<Binding Path="DataContext.DisplayCredentials"
RelativeSource="{RelativeSource AncestorType=UserControl}" />
</MultiBinding>
</Run.Text>
<Run.Text>
<MultiBinding Mode="OneWay"
Converter="{StaticResource ProxyDataTextMultiConverter}">
<Binding Path="DefaultProxy.Value" />
<Binding Path="DataContext.DisplayProtocol"
RelativeSource="{RelativeSource AncestorType=UserControl}" />
<Binding Path="DataContext.DisplayCredentials"
RelativeSource="{RelativeSource AncestorType=UserControl}" />
</MultiBinding>
</Run.Text>
</Run>
</TextBlock>
@@ -3,7 +3,6 @@ using System.Windows.Input;
namespace NebulaAuth.View;
public partial class ProxyManagerView
{
public ProxyManagerView()
@@ -40,7 +40,7 @@
<md:PackIcon Kind="ShieldKey" Width="20" Height="20"
Margin="0,0,5,0" VerticalAlignment="Center"
Foreground="{DynamicResource PrimaryContentBrush}" />
<TextBlock Text="{Tr SetAccountPasswordsView.Title}"
<TextBlock Text="{Tr SetAccountPasswordsView.Title}"
FontSize="18"
VerticalAlignment="Center"
Foreground="{DynamicResource BaseContentBrush}" />
@@ -61,74 +61,68 @@
<Grid Grid.Row="2">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition/>
<RowDefinition />
</Grid.RowDefinitions>
<md:Card Margin="15,15,15,15" BorderThickness="1" BorderBrush="Gray" Padding="12" >
<StackPanel>
<TextBlock Text="{Tr SetAccountPasswordsView.EncryptionPassword}" FontSize="16"
Margin="0,0,0,5"
Foreground="{DynamicResource PrimaryContentBrush}" />
<md:Card Margin="15,15,15,15" BorderThickness="1" BorderBrush="Gray" Padding="12">
<StackPanel>
<TextBlock Text="{Tr SetAccountPasswordsView.EncryptionPassword}" FontSize="16"
Margin="0,0,0,5"
Foreground="{DynamicResource PrimaryContentBrush}" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox
md:HintAssist.Hint="{Tr SetAccountPasswordsView.EnterPassword}"
md:HintAssist.IsFloating="False"
Margin="0,0,10,0"
Text="{Binding EncryptionPassword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox
md:HintAssist.Hint="{Tr SetAccountPasswordsView.EnterPassword}"
md:HintAssist.IsFloating="False"
Margin="0,0,10,0"
Text="{Binding EncryptionPassword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Column="1" Command="{Binding SetEncryptionPasswordCommand}">
<md:PackIcon Kind="ContentSave"/>
</Button>
<Button Grid.Column="1" Command="{Binding SetEncryptionPasswordCommand}">
<md:PackIcon Kind="ContentSave" />
</Button>
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<StackPanel.Resources>
<x:Array x:Key="BoolToIcon" Type="{x:Type md:PackIconKind}">
<md:PackIconKind>CheckBox</md:PackIconKind>
<md:PackIconKind>CloseBox</md:PackIconKind>
</x:Array>
<x:Array x:Key="BoolToColor" Type="{x:Type SolidColorBrush}">
<SolidColorBrush Color="{DynamicResource SuccessColor}"/>
<SolidColorBrush Color="{DynamicResource ErrorColor}"/>
</x:Array>
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<StackPanel.Resources>
<x:Array x:Key="BoolToIcon" Type="{x:Type md:PackIconKind}">
<md:PackIconKind>CheckBox</md:PackIconKind>
<md:PackIconKind>CloseBox</md:PackIconKind>
</x:Array>
<x:Array x:Key="BoolToColor" Type="{x:Type SolidColorBrush}">
<SolidColorBrush Color="{DynamicResource SuccessColor}" />
<SolidColorBrush Color="{DynamicResource ErrorColor}" />
</x:Array>
</StackPanel.Resources>
<TextBlock Text="{Tr SetAccountPasswordsView.Status}" VerticalAlignment="Center"/>
<md:PackIcon Width="20" Height="20"
VerticalAlignment="Center"
Foreground="{Binding IsEncryptionPasswordSet, Converter={StaticResource BoolToValueConverter}, ConverterParameter={StaticResource BoolToColor}}"
Kind="{Binding IsEncryptionPasswordSet, Converter={StaticResource BoolToValueConverter}, ConverterParameter={StaticResource BoolToIcon}}" />
</StackPanel.Resources>
<TextBlock Text="{Tr SetAccountPasswordsView.Status}" VerticalAlignment="Center" />
<md:PackIcon Width="20" Height="20"
VerticalAlignment="Center"
Foreground="{Binding IsEncryptionPasswordSet, Converter={StaticResource BoolToValueConverter}, ConverterParameter={StaticResource BoolToColor}}"
Kind="{Binding IsEncryptionPasswordSet, Converter={StaticResource BoolToValueConverter}, ConverterParameter={StaticResource BoolToIcon}}" />
</StackPanel>
</StackPanel>
</StackPanel>
</md:Card>
</Grid>
<!-- ===== ACCOUNTS INPUT ===== -->
<TextBox Grid.Row="3"
Margin="15,0,15,10"
Text="{Binding AccountsPasswords, UpdateSourceTrigger=PropertyChanged}"
FontSize="13"
AcceptsReturn="True"
Margin="15,0,15,10"
Text="{Binding AccountsPasswords, UpdateSourceTrigger=PropertyChanged}"
FontSize="13"
AcceptsReturn="True"
VerticalScrollBarVisibility="Auto"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
md:TextFieldAssist.HasClearButton="True"
md:HintAssist.IsFloating="False"
md:HintAssist.Hint="{Tr SetAccountPasswordsView.InputFormat}"
md:TextFieldAssist.TextBoxIsMultiLine="True"
md:TextFieldAssist.TextBoxViewVerticalAlignment="Top"
VerticalContentAlignment="Top"
>
</TextBox>
VerticalScrollBarVisibility="Auto"
Style="{StaticResource MaterialDesignOutlinedTextBox}"
md:TextFieldAssist.HasClearButton="True"
md:HintAssist.IsFloating="False"
md:HintAssist.Hint="{Tr SetAccountPasswordsView.InputFormat}"
md:TextFieldAssist.TextBoxIsMultiLine="True"
md:TextFieldAssist.TextBoxViewVerticalAlignment="Top"
VerticalContentAlignment="Top" />
<!-- ===== INFO TEXT ===== -->
<TextBlock Grid.Row="4"
Margin="20,0,20,15"
@@ -1,8 +1,4 @@
using System.Windows.Controls;
using System.Windows.Input;
namespace NebulaAuth.View;
namespace NebulaAuth.View;
public partial class SetAccountPasswordsView
{
+7 -8
View File
@@ -101,7 +101,7 @@
Style="{StaticResource MaterialDesignFloatingHintComboBox}"
SelectedItem="{Binding UseAccountNameAsMafileNamePreview}">
<ComboBox.ItemsSource>
<x:Array Type="{x:Type sys:Boolean}"
<x:Array Type="{x:Type sys:Boolean}"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:Boolean>True</sys:Boolean>
<sys:Boolean>False</sys:Boolean>
@@ -110,21 +110,20 @@
</ComboBox.ItemsSource>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource BoolToMafileNamingConverter}}"/>
<TextBlock Text="{Binding Converter={StaticResource BoolToMafileNamingConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Margin="0,10,0,0"
<Button Margin="0,10,0,0"
materialDesign:ButtonProgressAssist.Maximum="1"
materialDesign:ButtonProgressAssist.Value="{Binding RenameMafilesProgress}"
materialDesign:ButtonProgressAssist.Value="{Binding RenameMafilesProgress}"
materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding ApplyRenameSettingCommand.IsRunning}"
Style="{StaticResource MaterialDesignOutlinedButton}"
Command="{Binding ApplyRenameSettingCommand}"
Content="{Tr SettingsDialog.ApplyNamingMode}"
/>
<nebulaAuth:HintBox Margin="0,10,0,0" Text="{Binding RenameResultText}"
Content="{Tr SettingsDialog.ApplyNamingMode}" />
<nebulaAuth:HintBox Margin="0,10,0,0" Text="{Binding RenameResultText}"
FontSize="14"
Visibility="{Binding RenameResultText, Converter={StaticResource NullableToVisibilityConverter}, Mode=OneWay}"/>
Visibility="{Binding RenameResultText, Converter={StaticResource NullableToVisibilityConverter}, Mode=OneWay}" />
</StackPanel>
</TabItem>
-1
View File
@@ -5,7 +5,6 @@ using MaterialDesignThemes.Wpf;
namespace NebulaAuth.View;
public partial class SettingsView
{
private readonly DialogHost? _dialogHost;
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
@@ -1,4 +1,12 @@
using AchiesUtilities.Web.Proxy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using AchiesUtilities.Web.Proxy;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NebulaAuth.Core;
@@ -24,14 +32,6 @@ using SteamLibForked.Abstractions;
using SteamLibForked.Exceptions.Authorization;
using SteamLibForked.Models.Core;
using SteamLibForked.Models.Session;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace NebulaAuth.ViewModel.MafileMover;
+1 -1
View File
@@ -49,7 +49,7 @@ public partial class MainVM : ObservableObject
[RelayCommand]
public async Task Debug()
{
await DialogsController.ShowSetAccountsPasswordDialog();
await DialogsController.ShowSetAccountsPasswordDialog();
}
@@ -1,14 +1,14 @@
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Input;
using NebulaAuth.Core;
using NebulaAuth.Model;
using NebulaAuth.Model.Entities;
using NebulaAuth.Utility;
using SteamLib.SteamMobile.Confirmations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
namespace NebulaAuth.ViewModel;
+4 -4
View File
@@ -1,5 +1,4 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using AchiesUtilities.Extensions;
@@ -41,9 +40,10 @@ public partial class MainVM //Groups
[RelayCommand]
private async Task CreateGroup(Mafile? mafile)
{
if(mafile == null) return;
var res = await DialogsController.ShowTextFieldDialog(GetLocalization("CreateGroupTitle"), GetLocalization("CreateGroupInput"));
if(string.IsNullOrWhiteSpace(res)) return;
if (mafile == null) return;
var res = await DialogsController.ShowTextFieldDialog(GetLocalization("CreateGroupTitle"),
GetLocalization("CreateGroupInput"));
if (string.IsNullOrWhiteSpace(res)) return;
AddToGroup([res, mafile]);
SnackbarController.SendSnackbar(GetLocalization("CreateGroupSuccess"));
}
@@ -1,26 +1,24 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NebulaAuth.Model;
using SteamLibForked.Models.SteamIds;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace NebulaAuth.ViewModel.Other;
public partial class SetAccountPasswordsVM : ObservableObject
{
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SetPasswordsCommand))]
private bool _isEncryptionPasswordSet;
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(SetPasswordsCommand))]
private string? _accountsPasswords;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SetEncryptionPasswordCommand))]
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(SetEncryptionPasswordCommand))]
private string? _encryptionPassword;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SetPasswordsCommand))]
private string? _accountsPasswords;
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(SetPasswordsCommand))]
private bool _isEncryptionPasswordSet;
[ObservableProperty] private string? _tip;
public SetAccountPasswordsVM()
@@ -36,12 +34,16 @@ public partial class SetAccountPasswordsVM : ObservableObject
{
return;
}
Settings.Instance.IsPasswordSet = PHandler.SetPassword(EncryptionPassword);
IsEncryptionPasswordSet = PHandler.IsPasswordSet;
EncryptionPassword = null;
}
private bool SetEncryptionPasswordCanExecute() => !string.IsNullOrWhiteSpace(EncryptionPassword);
private bool SetEncryptionPasswordCanExecute()
{
return !string.IsNullOrWhiteSpace(EncryptionPassword);
}
[RelayCommand(CanExecute = nameof(SetPasswordsCanExecute))]
@@ -69,8 +71,8 @@ public partial class SetAccountPasswordsVM : ObservableObject
continue;
}
string login = split[0];
string password = split[1];
var login = split[0];
var password = split[1];
SteamId64? steamId = null;
if (SteamId64.TryParse(login, out var id64))
@@ -106,7 +108,6 @@ public partial class SetAccountPasswordsVM : ObservableObject
{
Tip = $"Успешно: {success}, Не найдено: {notFound}, Ошибки: {errors}";
}
}
private bool SetPasswordsCanExecute()
+91 -93
View File
@@ -1,11 +1,11 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NebulaAuth.Core;
using NebulaAuth.Model;
using System;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NebulaAuth.Core;
using NebulaAuth.Model;
namespace NebulaAuth.ViewModel.Other;
@@ -13,6 +13,92 @@ public partial class SettingsVM : ObservableObject
{
public Settings Settings => Settings.Instance;
[ObservableProperty] private string? _password;
[ObservableProperty] private double _renameMafilesProgress;
[ObservableProperty] private string? _renameResultText;
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ApplyRenameSettingCommand))]
private bool _useAccountNameAsMafileNamePreview;
public SettingsVM()
{
_useAccountNameAsMafileNamePreview = Settings.UseAccountNameAsMafileName;
}
[RelayCommand]
private void SetPassword()
{
Settings.IsPasswordSet = PHandler.SetPassword(Password);
}
[RelayCommand]
private void ResetThemeDefaults()
{
Settings.ResetThemeDefaults();
OnPropertyChanged(nameof(BackgroundBlur));
OnPropertyChanged(nameof(BackgroundOpacity));
OnPropertyChanged(nameof(BackgroundGamma));
OnPropertyChanged(nameof(LeftOpacity));
OnPropertyChanged(nameof(RightOpacity));
OnPropertyChanged(nameof(ApplyBlurBackground));
OnPropertyChanged(nameof(RippleDisabled));
}
[RelayCommand(CanExecute = nameof(ApplyRenameSettingCanExecute))]
private async Task ApplyRenameSetting()
{
RenameResultText = null;
var targetValue = UseAccountNameAsMafileNamePreview;
if (UseAccountNameAsMafileName == targetValue) return;
RenameMafilesProgress = 0;
Storage.MafileRenameResult? result = null;
try
{
result = await Storage.RenameMafiles(targetValue, new Progress<double>(p => RenameMafilesProgress = p));
UseAccountNameAsMafileName = targetValue;
}
catch (Exception ex)
{
Shell.Logger.Error(ex, "Error while renaming mafiles");
}
finally
{
RenameMafilesProgress = 0;
}
if (result == null)
{
RenameResultText = GetLoc("Error");
return;
}
if (result.Total == 0) return;
if (result.NotRenamed == 0)
{
var l = GetLoc("AllRenamed");
RenameResultText = string.Format(l, result.Total, result.BackupFileName);
}
else
{
var l = GetLoc("PartialSuccess");
RenameResultText =
string.Format(l, result.Total, result.Renamed, result.Errors, result.Conflict, result.BackupFileName);
}
string GetLoc(string key)
{
return LocManager.GetCodeBehindOrDefault(key, "SettingsVM", "MafileRenaming", key);
}
}
private bool ApplyRenameSettingCanExecute()
{
return UseAccountNameAsMafileNamePreview != UseAccountNameAsMafileName;
}
#region SettingsProps
public bool HideToTray
@@ -104,8 +190,6 @@ public partial class SettingsVM : ObservableObject
set => Settings.IgnorePatchTuesdayErrors = value;
}
#endregion
#region Theme
@@ -165,90 +249,4 @@ public partial class SettingsVM : ObservableObject
}
#endregion
[ObservableProperty] private string? _password;
[ObservableProperty] private string? _renameResultText;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ApplyRenameSettingCommand))]
private bool _useAccountNameAsMafileNamePreview;
[ObservableProperty]
private double _renameMafilesProgress;
public SettingsVM()
{
_useAccountNameAsMafileNamePreview = Settings.UseAccountNameAsMafileName;
}
[RelayCommand]
private void SetPassword()
{
Settings.IsPasswordSet = PHandler.SetPassword(Password);
}
[RelayCommand]
private void ResetThemeDefaults()
{
Settings.ResetThemeDefaults();
OnPropertyChanged(nameof(BackgroundBlur));
OnPropertyChanged(nameof(BackgroundOpacity));
OnPropertyChanged(nameof(BackgroundGamma));
OnPropertyChanged(nameof(LeftOpacity));
OnPropertyChanged(nameof(RightOpacity));
OnPropertyChanged(nameof(ApplyBlurBackground));
OnPropertyChanged(nameof(RippleDisabled));
}
[RelayCommand(CanExecute = nameof(ApplyRenameSettingCanExecute))]
private async Task ApplyRenameSetting()
{
RenameResultText = null;
var targetValue = UseAccountNameAsMafileNamePreview;
if (UseAccountNameAsMafileName == targetValue) return;
RenameMafilesProgress = 0;
Storage.MafileRenameResult? result = null;
try
{
result = await Storage.RenameMafiles(targetValue, new Progress<double>(p => RenameMafilesProgress = p));
UseAccountNameAsMafileName = targetValue;
}
catch (Exception ex)
{
Shell.Logger.Error(ex, "Error while renaming mafiles");
}
finally
{
RenameMafilesProgress = 0;
}
if (result == null)
{
RenameResultText = GetLoc("Error");
return;
}
if (result.Total == 0) return;
if (result.NotRenamed == 0)
{
var l = GetLoc("AllRenamed");
RenameResultText = string.Format(l, result.Total, result.BackupFileName);
return;
}
else
{
var l = GetLoc("PartialSuccess");
RenameResultText =
string.Format(l, result.Total, result.Renamed, result.Errors, result.Conflict, result.BackupFileName);
}
string GetLoc(string key)
{
return LocManager.GetCodeBehindOrDefault(key, "SettingsVM", "MafileRenaming", key);
}
}
private bool ApplyRenameSettingCanExecute() => UseAccountNameAsMafileNamePreview != UseAccountNameAsMafileName;
}
+70 -36
View File
@@ -481,7 +481,8 @@
},
"LegacyMafileModeHint": {
"en": "Save mafiles in compatibility format with Steam Desktop Authenticator and other applications",
"ru": "Сохранять мафайлы в старом формате для совместимости со Steam Desktop Authenticator и другими приложениями",
"ru":
"Сохранять мафайлы в старом формате для совместимости со Steam Desktop Authenticator и другими приложениями",
"ua": "Зберігати мафайли у старому форматі для сумісності зі Steam Desktop Authenticator та іншими додатками"
},
"AllowAutoUpdate": {
@@ -505,9 +506,12 @@
"ua": "Ігнорувати помилки Patch Tuesday у таймері (експ.)"
},
"IgnorePatchTuesdayErrorsHint": {
"en": "Ignore errors that occur every Tuesday (Wednesday night in GMT) when Steam doing technical works and auto-confirm timers turns off unnecessarily",
"ru": "Игнорировать ошибки, которые возникают каждый вторник (ночь среды по GMT) когда Steam проводит технические работы и автоподтверждения отключаются без надобности",
"ua": "Ігнорувати помилки, які виникають щосереди (ніч середи за GMT) коли Steam проводить технічні роботи і автопідтвердження вимикаються без потреби"
"en":
"Ignore errors that occur every Tuesday (Wednesday night in GMT) when Steam doing technical works and auto-confirm timers turns off unnecessarily",
"ru":
"Игнорировать ошибки, которые возникают каждый вторник (ночь среды по GMT) когда Steam проводит технические работы и автоподтверждения отключаются без надобности",
"ua":
"Ігнорувати помилки, які виникають щосереди (ніч середи за GMT) коли Steam проводить технічні роботи і автопідтвердження вимикаються без потреби"
}
@@ -692,9 +696,12 @@
"ua": "Пароль шифрування"
},
"DialogText": {
"en": "You have previously set an encryption password for passwords in mafiles, specify it so that the application can automatically log in in case of problems with the session.\r\n(Optional)",
"ru": "Ранее вы устанавливали пароль шифрования для паролей в мафайлах, укажите его, чтобы приложение могло автоматически авторизоваться в случае проблем с сессией.\r\n(Не обязательно)",
"ua": "Раніше ви встановлювали пароль шифрування для паролів в мафайлах, вкажіть його, щоб додаток міг автоматично авторизуватися у випадку проблем з сесією.\r\n(Не обов'язково)"
"en":
"You have previously set an encryption password for passwords in mafiles, specify it so that the application can automatically log in in case of problems with the session.\r\n(Optional)",
"ru":
"Ранее вы устанавливали пароль шифрования для паролей в мафайлах, укажите его, чтобы приложение могло автоматически авторизоваться в случае проблем с сессией.\r\n(Не обязательно)",
"ua":
"Раніше ви встановлювали пароль шифрування для паролів в мафайлах, вкажіть його, щоб додаток міг автоматично авторизуватися у випадку проблем з сесією.\r\n(Не обов'язково)"
},
"Ok": {
"en": "Ok",
@@ -775,7 +782,7 @@
"en": "All passwords in mafiles will be encrypted using the encryption password.",
"ru": "Все пароли в мафайлах будут зашифрованы с помощью пароля шифрования.",
"ua": "Всі паролі в мафайлах будуть зашифровані за допомогою пароля шифрування."
},
},
"InputFormat": {
"en": "Supported formats:\r\n\r\nlogin:password\r\nsteamid:password",
"ru": "Поддерживаемые форматы:\r\n\r\nlogin:password\r\nsteamid:password",
@@ -801,9 +808,12 @@
"ua": "Відсутній RCode"
},
"ConfirmRemovingAuthenticator": {
"ru": "Вы точно уверены, что хотите удалить аутентификатор?\r\nПосле этого вы не сможете обмениваться, использовать торговую площадку 15 дней. Мафайл будет удалён навсегда",
"en": "Are you sure you want to remove the authenticator?\r\nAfter that, you will not be able to trade or use the marketplace for 15 days. Mafile will be deleted permanently",
"ua": "Ви точно впевнені, що хочете видалити автентифікатор?\r\nПісля цього ви не зможете обмінюватися, використовувати торгову площадку 15 днів. Мафайл буде видалено назавжди"
"ru":
"Вы точно уверены, что хотите удалить аутентификатор?\r\nПосле этого вы не сможете обмениваться, использовать торговую площадку 15 дней. Мафайл будет удалён навсегда",
"en":
"Are you sure you want to remove the authenticator?\r\nAfter that, you will not be able to trade or use the marketplace for 15 days. Mafile will be deleted permanently",
"ua":
"Ви точно впевнені, що хочете видалити автентифікатор?\r\nПісля цього ви не зможете обмінюватися, використовувати торгову площадку 15 днів. Мафайл буде видалено назавжди"
},
"AuthenticatorRemoved": {
@@ -872,9 +882,12 @@
"ua": "помилки:"
},
"RemoveMafileConfirmation": {
"ru": "Удалить mafile?\r\nМафайл будет перемещен в папку 'mafiles_removed'\r\nЭто действие НЕ удаляет Steam Guard с аккаунта",
"en": "Remove mafile?\r\nMafile will be moved to 'mafiles_removed' directory\r\nThis action will NOT remove the Steam Guard from the account",
"ua": "Видалити mafile?\r\nМафайл буде переміщено у каталог 'mafiles_removed'\r\nЦя дія НЕ видаляє автентифікатор з облікового запису"
"ru":
"Удалить mafile?\r\nМафайл будет перемещен в папку 'mafiles_removed'\r\nЭто действие НЕ удаляет Steam Guard с аккаунта",
"en":
"Remove mafile?\r\nMafile will be moved to 'mafiles_removed' directory\r\nThis action will NOT remove the Steam Guard from the account",
"ua":
"Видалити mafile?\r\nМафайл буде переміщено у каталог 'mafiles_removed'\r\nЦя дія НЕ видаляє автентифікатор з облікового запису"
},
"CantRemoveAlreadyExist": {
"ru": "Не удалось переместить mafile, возможно в папке уже существует мафайл с таким именем.",
@@ -928,7 +941,8 @@
},
"CantDecryptPassword": {
"en": "Can't decrypt password. Maybe password from this mafile was encrypted with another encryption password",
"ru": "Не удалось расшифровать пароль. Возможно пароль из этого мафайла был зашифрован другим паролем шифрования",
"ru":
"Не удалось расшифровать пароль. Возможно пароль из этого мафайла был зашифрован другим паролем шифрования",
"ua": "Не вдалося розшифрувати пароль. Можливо пароль з цього мафайла був зашифрований іншим паролем шифрування"
},
"CreateGroupTitle": {
@@ -1199,8 +1213,10 @@
},
"InvalidStateWithStatus2": {
"ru": "Неверное состояние (InvalidState) со статусом 2. Откройте ссылку на руководство сверху этого окна.",
"en": "Invalid state (InvalidState) with status 2. Open link to the troubleshooting guide at the top of this window.",
"ua": "Невірний стан (InvalidState) зі статусом 2. Відкрийте посилання на посібник з усунення несправностей у верхній частині цього вікна."
"en":
"Invalid state (InvalidState) with status 2. Open link to the troubleshooting guide at the top of this window.",
"ua":
"Невірний стан (InvalidState) зі статусом 2. Відкрийте посилання на посібник з усунення несправностей у верхній частині цього вікна."
},
"GeneralFailure": {
"ru": "General Failure",
@@ -1249,7 +1265,8 @@
"Guard": {
"ru": "Ошибка: Был запрошен вход с помощью Steam Guard. На аккаунте уже активирован мобильный аутентификатор",
"en": "Error: Login with Steam Guard was requested. Mobile authenticator is already activated on the account",
"ua": "Помилка: Був запрошений вхід за допомогою Steam Guard. На акаунті вже активовано мобільний автентифікатор"
"ua":
"Помилка: Був запрошений вхід за допомогою Steam Guard. На акаунті вже активовано мобільний автентифікатор"
},
"Unknown": {
"ru": "Ошибка: Неизвестный тип аутентификации",
@@ -1352,9 +1369,12 @@
"ua": "На пошту надіслано лист. Відкрийте посилання з листа, а потім натисніть — 'Продовжити'"
},
"ClickOnEmailLinkRetry": {
"ru": "Не удалось подтвердить переход по ссылке. Убедитесь, что вы открыли ссылку из письма, затем нажмите — 'Продолжить'",
"en": "We couldnt verify that you clicked the link. Make sure you opened the link from the email, then click 'Proceed'",
"ua": "Не вдалося підтвердити перехід за посиланням. Переконайтесь, що ви відкрили посилання з листа, а потім натисніть — 'Продовжити'"
"ru":
"Не удалось подтвердить переход по ссылке. Убедитесь, что вы открыли ссылку из письма, затем нажмите — 'Продолжить'",
"en":
"We couldnt verify that you clicked the link. Make sure you opened the link from the email, then click 'Proceed'",
"ua":
"Не вдалося підтвердити перехід за посиланням. Переконайтесь, що ви відкрили посилання з листа, а потім натисніть — 'Продовжити'"
},
"PhoneHint": {
"ru": "На телефон {0} была отправлена СМС",
@@ -1362,9 +1382,12 @@
"ua": "На телефон {0} було відправлено СМС"
},
"EnterPhoneNumber": {
"ru": "Введите номер в международном формате, только цифры (без '+', пробелов и скобок), или оставьте поле пустым, чтобы привязать без номера",
"en": "Enter number in international format, digits only (no '+', spaces or brackets), or leave the field empty to link without a number",
"ua": "Введіть номер у міжнародному форматі, лише цифри (без '+', пробілів і дужок), або залиште поле порожнім, щоб прив’язати без номера"
"ru":
"Введите номер в международном формате, только цифры (без '+', пробелов и скобок), или оставьте поле пустым, чтобы привязать без номера",
"en":
"Enter number in international format, digits only (no '+', spaces or brackets), or leave the field empty to link without a number",
"ua":
"Введіть номер у міжнародному форматі, лише цифри (без '+', пробілів і дужок), або залиште поле порожнім, щоб прив’язати без номера"
}
},
"MafileMoverVM": {
@@ -1389,9 +1412,11 @@
"ua": "RCode: {0}\r\nІм'я файлу: {1}.mafile"
},
"GuardIsNotActive": {
"ru": "Steam Guard установлен на данном аккаунте. Чтобы привязать mafile к аккаунту, воспользуйтесь окном \"Привязать\"",
"ru":
"Steam Guard установлен на данном аккаунте. Чтобы привязать mafile к аккаунту, воспользуйтесь окном \"Привязать\"",
"en": "Steam Guard is set on this account. To link mafile to the account, use the 'Link' window",
"ua": "Steam Guard встановлено на цьому акаунті. Щоб прив'язати mafile до акаунту, скористайтеся вікном 'Прив'язати'"
"ua":
"Steam Guard встановлено на цьому акаунті. Щоб прив'язати mafile до акаунту, скористайтеся вікном 'Прив'язати'"
},
"SeemsNoPhoneNumber": {
"en": "The account has no phone number linked, returned Fail code (2)",
@@ -1426,15 +1451,18 @@
"ua": "Авто "
},
"TimerPreventedOverlap": {
"ru": "Авто: таймер подтверждений пытался начать новый цикл, когда предыдущий еще не завершился. Советуем увеличить задержку",
"en": "Auto: confirmation timer tried to start new cycle when previous one was not finished yet. We recommend to increase delay",
"ua": "Авто: таймер підтверджень намагався запустити новий цикл, коли попередній ще не закінчився. Рекомендуємо збільшити затримку"
"ru":
"Авто: таймер подтверждений пытался начать новый цикл, когда предыдущий еще не завершился. Советуем увеличить задержку",
"en":
"Auto: confirmation timer tried to start new cycle when previous one was not finished yet. We recommend to increase delay",
"ua":
"Авто: таймер підтверджень намагався запустити новий цикл, коли попередній ще не закінчився. Рекомендуємо збільшити затримку"
},
"FailedToLoadStorage": {
"en": "Failed to load auto-confirm timers. File seems to be corrupted",
"ru": "Не удалось загрузить таймеры авто-подтверждений. Файл, похоже, поврежден",
"ua": "Не вдалося завантажити таймери авто-підтверджень. Файл, схоже, пошкоджено"
}
}
},
"SettingsVM": {
"MafileRenaming": {
@@ -1449,9 +1477,12 @@
"ua": "Всі мафайли успішно перейменовані ({0}).\r\nБуло створено резервну копію: {1}"
},
"PartialSuccess": {
"en": "Total mafiles: {0}\r\nRenamed: {1}\r\nConflicts: {2}\r\nErrors: {3}\r\n\r\nBackup of mafiles saved in file: {4}",
"ru": "Всего мафайлов: {0}\r\nПереименовано: {1}\r\nКонфликты: {2}\r\nОшибок: {3}\r\n\r\nРезервная копия мафайлов сохранена в файле: {4}",
"ua": "Всього мафайлів: {0}\r\nПерейменовано: {1}\r\nКонфлікти: {2}\r\nПомилок: {3}\r\n\r\nРезервна копія мафайлів збережена у файлі: {4}"
"en":
"Total mafiles: {0}\r\nRenamed: {1}\r\nConflicts: {2}\r\nErrors: {3}\r\n\r\nBackup of mafiles saved in file: {4}",
"ru":
"Всего мафайлов: {0}\r\nПереименовано: {1}\r\nКонфликты: {2}\r\nОшибок: {3}\r\n\r\nРезервная копия мафайлов сохранена в файле: {4}",
"ua":
"Всього мафайлів: {0}\r\nПерейменовано: {1}\r\nКонфлікти: {2}\r\nПомилок: {3}\r\n\r\nРезервна копія мафайлів збережена у файлі: {4}"
}
}
},
@@ -1471,8 +1502,11 @@
}
},
"CantAlignTimeError": {
"ru": "Не удается синхронизировать время со Steam. Возможно отсутствует подключение к интернету или Steam недоступен. Подробная ошибка сохранена в log.log",
"en": "Can't align time with Steam. Maybe no internet connection or Steam is unavailable. Detailed error saved in log.log",
"ua": "Не вдається синхронізувати час з Steam. Можливо відсутнє підключення до інтернету або Steam недоступний. Детальна помилка збережена в log.log"
"ru":
"Не удается синхронизировать время со Steam. Возможно отсутствует подключение к интернету или Steam недоступен. Подробная ошибка сохранена в log.log",
"en":
"Can't align time with Steam. Maybe no internet connection or Steam is unavailable. Detailed error saved in log.log",
"ua":
"Не вдається синхронізувати час з Steam. Можливо відсутнє підключення до інтернету або Steam недоступний. Детальна помилка збережена в log.log"
}
}
@@ -67,14 +67,14 @@ public static class SteamAuthenticatorLinkerApi
var reqUri = AddAccessToken(Routes.LINK_REQUEST, data.GetAccessToken());
var req = new AddAuthenticator_Request
{
SteamId = (ulong)data.SteamId.Steam64.Id,
SteamId = (ulong) data.SteamId.Steam64.Id,
AuthenticatorType = 1,
DeviceIdentifier = deviceId,
Version = 2
};
var resp = await client.PostProtoMsg<AddAuthenticator_Response>(reqUri, req);
if (resp is { Result: EResult.InvalidState, ResponseMsg.Status: 2 })
if (resp is {Result: EResult.InvalidState, ResponseMsg.Status: 2})
{
throw new AuthenticatorLinkerException(AuthenticatorLinkerError.InvalidStateWithStatus2);
}
@@ -100,7 +100,7 @@ public static class SteamAuthenticatorLinkerApi
{
SteamId = data.SteamId.Steam64.ToUlong(),
AuthenticatorCode = code,
AuthenticatorTime = (ulong)time,
AuthenticatorTime = (ulong) time,
ConfirmationCode = confirmationCode,
ValidateConfirmationCode = validateSmsCode
};
@@ -108,7 +108,7 @@ public static class SteamAuthenticatorLinkerApi
var resp = await client.PostProto<FinalizeAddAuthenticator_Response>(reqUri, req);
if (resp is { Success: true, WantMore: false })
if (resp is {Success: true, WantMore: false})
{
return new LinkResult();
}
@@ -1,11 +1,11 @@
using Newtonsoft.Json.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using SteamLib.Core;
using SteamLib.Core.StatusCodes;
using SteamLib.Exceptions;
using SteamLib.Exceptions.Authorization;
using SteamLib.ProtoCore;
using SteamLib.ProtoCore.Services;
using System.Net;
namespace SteamLib.Api.Mobile;
@@ -1,4 +1,5 @@
using AchiesUtilities.Web.Extensions;
using System.Net;
using AchiesUtilities.Web.Extensions;
using SteamLib.Core;
using SteamLib.Core.StatusCodes;
using SteamLib.Exceptions;
@@ -7,7 +8,6 @@ using SteamLib.SteamMobile;
using SteamLib.SteamMobile.Confirmations;
using SteamLib.Utility;
using SteamLib.Web.Scrappers.JSON;
using System.Net;
namespace SteamLib.Api.Mobile;
@@ -1,9 +1,9 @@
using SteamLib.Core;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using SteamLib.Core;
using SteamLib.Exceptions.Authorization;
using SteamLib.ProtoCore;
using SteamLib.ProtoCore.Services;
using System.Diagnostics.CodeAnalysis;
using System.Net;
namespace SteamLib.Api.Services;
+3 -3
View File
@@ -1,8 +1,8 @@
using SteamLib.Core;
using System.Net;
using System.Web;
using SteamLib.Core;
using SteamLib.Models;
using SteamLib.Web.Scrappers.HTML;
using System.Net;
using System.Web;
namespace SteamLib.Api;
@@ -1,4 +1,5 @@
using AchiesUtilities.Extensions;
using System.Net;
using AchiesUtilities.Extensions;
using AchiesUtilities.Models;
using Newtonsoft.Json;
using SteamLib.Core;
@@ -6,7 +7,6 @@ using SteamLib.Models.Account;
using SteamLibForked.Abstractions;
using SteamLibForked.Models.Core;
using SteamLibForked.Models.Session;
using System.Net;
namespace SteamLib.Authentication;
@@ -131,7 +131,7 @@ public static class AdmissionHelper
}
var mobileToken = mobileSession.GetMobileToken();
if (domainCookieSet == false && mobileToken is { IsExpired: false })
if (domainCookieSet == false && mobileToken is {IsExpired: false})
{
var domain = SteamDomains.GetDomainUri(SteamDomain.Community);
container.Add(domain, new Cookie(ACCESS_COOKIE_NAME, mobileToken.Value.SignedToken)
@@ -208,7 +208,7 @@ public static class AdmissionHelper
static Cookie CloneCookie(Cookie cookie)
{
return new Cookie(cookie.Name, cookie.Value, cookie.Path)
{ Expires = cookie.Expires, Secure = cookie.Secure, HttpOnly = cookie.HttpOnly };
{Expires = cookie.Expires, Secure = cookie.Secure, HttpOnly = cookie.HttpOnly};
}
}
@@ -1,6 +1,6 @@
using SteamLib.ProtoCore.Enums;
using System.Security.Cryptography;
using SteamLib.ProtoCore.Enums;
using SteamLib.ProtoCore.Services;
using System.Security.Cryptography;
namespace SteamLib.Authentication;
@@ -1,11 +1,11 @@
using AchiesUtilities.Models;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using AchiesUtilities.Models;
using Microsoft.IdentityModel.JsonWebTokens;
using SteamLibForked.Models.Core;
using SteamLibForked.Models.Session;
using SteamLibForked.Models.SteamIds;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
namespace SteamLib.Authentication;
@@ -67,7 +67,7 @@ public partial class SteamStatusCode : Enumeration<SteamStatusCode>
public static SteamStatusCode FromEResult(EResult result)
{
var r = (int)result;
var r = (int) result;
var fromId = FromId(r);
return fromId ?? new SteamStatusCode(r, "Unknown");
}
+2 -2
View File
@@ -1,5 +1,5 @@
using SteamLibForked.Models.Core;
using System.Collections.ObjectModel;
using System.Collections.ObjectModel;
using SteamLibForked.Models.Core;
namespace SteamLib.Core;
@@ -1,7 +1,7 @@
using Microsoft.Extensions.Logging;
using SteamLib.Exceptions.General;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Logging;
using SteamLib.Exceptions.General;
namespace SteamLib.Core;
@@ -9,13 +9,13 @@ public static class DeviceDetailsDefaultBuilder
[Obsolete("Not recommended")]
public static DeviceDetails CreateDefault(string? deviceFriendlyName)
{
return new DeviceDetails(deviceFriendlyName ?? string.Empty, EAuthTokenPlatformType.WebBrowser, (int?)null,
return new DeviceDetails(deviceFriendlyName ?? string.Empty, EAuthTokenPlatformType.WebBrowser, (int?) null,
null);
}
public static DeviceDetails CreateCommunityDetails(string userAgent)
{
return new DeviceDetails(userAgent, EAuthTokenPlatformType.WebBrowser, (int?)null, null);
return new DeviceDetails(userAgent, EAuthTokenPlatformType.WebBrowser, (int?) null, null);
}
public static DeviceDetails CreateMobileDetails(string deviceName)
@@ -1,7 +1,7 @@
using Newtonsoft.Json;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;
using SteamLibForked.Abstractions;
using SteamLibForked.Models.Core;
using System.Diagnostics.CodeAnalysis;
namespace SteamLibForked.Models.Session;
@@ -38,7 +38,7 @@ public sealed class MobileSessionData : SessionData, IMobileSessionData
if (token.Type != SteamAccessTokenType.Mobile)
throw new ArgumentException("Token must be of type MobileAccess", nameof(token))
{
Data = { { "ActualType", token.Type } }
Data = {{"ActualType", token.Type}}
};
MobileToken = token;
@@ -46,7 +46,7 @@ public sealed class MobileSessionData : SessionData, IMobileSessionData
public override MobileSessionData Clone()
{
return (MobileSessionData)((ISessionData)this).Clone();
return (MobileSessionData) ((ISessionData) this).Clone();
}
object ICloneable.Clone()
@@ -1,8 +1,8 @@
using Newtonsoft.Json;
using System.Collections.Concurrent;
using Newtonsoft.Json;
using SteamLib.Web.Converters;
using SteamLibForked.Abstractions;
using SteamLibForked.Models.Core;
using System.Collections.Concurrent;
namespace SteamLibForked.Models.Session;
@@ -61,7 +61,7 @@ public class SessionData : ISessionData
public virtual SessionData Clone()
{
return (SessionData)((ICloneable)this).Clone();
return (SessionData) ((ICloneable) this).Clone();
}
object ICloneable.Clone()
+1 -1
View File
@@ -43,7 +43,7 @@ public readonly struct SteamId : IEquatable<SteamId> //TODO: validation in parse
public static SteamId FromSteam64(ulong steam64, char type = 'U', short universe = 0)
{
return new SteamId(new SteamId64((long)steam64), type, universe);
return new SteamId(new SteamId64((long) steam64), type, universe);
}
public static SteamId FromSteam2(byte lowestBit, int highestBit, byte universe = 0, char type = 'U')
@@ -19,7 +19,7 @@ public readonly struct SteamId3 : IEquatable<SteamId3>
{
var bit = Id % 2;
var highestBits = Id / 2;
return new SteamId2(universe, (byte)bit, highestBits);
return new SteamId2(universe, (byte) bit, highestBits);
}
@@ -16,15 +16,15 @@ public readonly struct SteamId64 : IEquatable<SteamId64>
public SteamId2 ToSteam2(short universe = 0)
{
var accountIdLowBit = (byte)(Id & 1);
var accountIdHighBits = (int)(Id >> 1) & 0x7FFFFFF;
return new SteamId2((byte)universe, accountIdLowBit, accountIdHighBits);
var accountIdLowBit = (byte) (Id & 1);
var accountIdHighBits = (int) (Id >> 1) & 0x7FFFFFF;
return new SteamId2((byte) universe, accountIdLowBit, accountIdHighBits);
}
public SteamId3 ToSteam3(char type = 'U')
{
var accountIdLowBit = (byte)(Id & 1);
var accountIdHighBits = (int)(Id >> 1) & 0x7FFFFFF;
var accountIdLowBit = (byte) (Id & 1);
var accountIdHighBits = (int) (Id >> 1) & 0x7FFFFFF;
return new SteamId3(accountIdLowBit + accountIdHighBits * 2, type);
}
@@ -36,7 +36,7 @@ public readonly struct SteamId64 : IEquatable<SteamId64>
public ulong ToUlong()
{
return (ulong)Id;
return (ulong) Id;
}
public long ToLong()
+3 -3
View File
@@ -1,7 +1,7 @@
using ProtoBuf;
using System.Diagnostics.CodeAnalysis;
using ProtoBuf;
using SteamLib.ProtoCore.Enums;
using SteamLib.ProtoCore.Interfaces;
using System.Diagnostics.CodeAnalysis;
namespace SteamLib.ProtoCore;
@@ -25,7 +25,7 @@ public static class ProtoHelpers
if (response.Headers.TryGetValues("x-eresult", out var val))
{
var eResultInt = Convert.ToInt32(val.Single());
return (EResult)eResultInt;
return (EResult) eResultInt;
}
return EResult.Invalid;
@@ -22,7 +22,7 @@ public class ProtoResponse<TProtoResponse> : ProtoResponse
{
public TProtoResponse? ResponseMsg
{
get => ProtoObject == null ? default : (TProtoResponse)ProtoObject;
get => ProtoObject == null ? default : (TProtoResponse) ProtoObject;
set => ProtoObject = value;
}
@@ -37,7 +37,7 @@ public class ProtoResponse<TProtoResponse> : ProtoResponse
if (response.Headers.TryGetValues("x-eresult", out var val))
{
var eResultInt = Convert.ToInt32(val.Single());
eResult = (EResult)eResultInt;
eResult = (EResult) eResultInt;
}
var msg = default(TProtoResponse);
@@ -67,7 +67,7 @@ public class ProtoResponse<TProtoResponse> : ProtoResponse
if (response.Headers.TryGetValues("x-eresult", out var val))
{
var eResultInt = Convert.ToInt32(val.Single());
eResult = (EResult)eResultInt;
eResult = (EResult) eResultInt;
}
var msg = default(TProtoResponse);
@@ -1,8 +1,8 @@
using ProtoBuf;
using System.Security.Cryptography;
using ProtoBuf;
using SteamLib.ProtoCore.Enums;
using SteamLib.ProtoCore.Interfaces;
using SteamLib.Utility;
using System.Security.Cryptography;
// ReSharper disable InconsistentNaming
// ReSharper disable IdentifierTypo
@@ -81,18 +81,18 @@ public class DeviceDetails : IProtoMsg
{
DeviceFriendlyName = deviceFriendlyName;
PlatformType = platformType;
OsType = (int?)osType;
OsType = (int?) osType;
GamingDeviceType = gamingDeviceType;
}
public static DeviceDetails CreateDefault()
{
return new DeviceDetails("", EAuthTokenPlatformType.WebBrowser, (int?)null, null);
return new DeviceDetails("", EAuthTokenPlatformType.WebBrowser, (int?) null, null);
}
public static DeviceDetails CreateCommunityDetails(string userAgent)
{
return new DeviceDetails(userAgent, EAuthTokenPlatformType.WebBrowser, (int?)null, null);
return new DeviceDetails(userAgent, EAuthTokenPlatformType.WebBrowser, (int?) null, null);
}
public static DeviceDetails CreateMobileDetails(string deviceName)
@@ -1,5 +1,12 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=exceptions_005Cauthorization/@EntryIndexedValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=models_005Ccore/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=models_005Ccore_005Csteamids/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=models_005Cnative/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml"
xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=exceptions_005Cauthorization/@EntryIndexedValue">False</s:Boolean>
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=models_005Ccore/@EntryIndexedValue">True</s:Boolean>
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=models_005Ccore_005Csteamids/@EntryIndexedValue">True</s:Boolean>
<s:Boolean
x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=models_005Cnative/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
@@ -103,7 +103,7 @@ public class SteamAuthenticatorLinker
var sendSms = await this.SendSmsCode();
if (sendSms != EResult.OK)
throw new AuthenticatorLinkerException($"Can't send SMS code: {sendSms} ({(int)sendSms})");
throw new AuthenticatorLinkerException($"Can't send SMS code: {sendSms} ({(int) sendSms})");
Logger?.LogDebug("SMS code sent");
}
@@ -155,14 +155,14 @@ public class SteamAuthenticatorLinker
var error = result.Error switch
{
LinkError.GeneralFailure => throw new AuthenticatorLinkerException(result.Code!.Value)
{ OnFinalization = true },
{OnFinalization = true},
LinkError.BadConfirmationCode => AuthenticatorLinkerError.BadConfirmationCode,
LinkError.UnableToGenerateCorrectCodes => AuthenticatorLinkerError.UnableToGenerateCorrectCodes,
_ => throw new ArgumentOutOfRangeException(nameof(result.Error), result.Error,
$"LinkError {result.Error} not supported")
};
throw new AuthenticatorLinkerException(error) { OnFinalization = true };
throw new AuthenticatorLinkerException(error) {OnFinalization = true};
}
Logger?.LogInformation("Linking completed");
@@ -1,11 +1,11 @@
using SteamLib.Abstractions;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using SteamLib.Abstractions;
using SteamLib.Api.Services;
using SteamLib.Authentication;
using SteamLib.ProtoCore.Enums;
using SteamLibForked.Abstractions.Auth;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace SteamLib.SteamMobile;
@@ -53,7 +53,7 @@ public class SteamGuardCodeGenerator : ISteamGuardProvider
for (var i = 8; i > 0; i--)
{
timeArray[i - 1] = (byte)time;
timeArray[i - 1] = (byte) time;
time >>= 8;
}
@@ -62,7 +62,7 @@ public class SteamGuardCodeGenerator : ISteamGuardProvider
var hashedData = hmacGenerator.ComputeHash(timeArray);
var codeArray = new byte[5];
var b = (byte)(hashedData[19] & 0xF);
var b = (byte) (hashedData[19] & 0xF);
var codePoint = ((hashedData[b] & 0x7F) << 24) | ((hashedData[b + 1] & 0xFF) << 16) |
((hashedData[b + 2] & 0xFF) << 8) | (hashedData[b + 3] & 0xFF);
@@ -1,7 +1,7 @@
using AchiesUtilities.Models;
using System.Diagnostics;
using AchiesUtilities.Models;
using Newtonsoft.Json.Linq;
using SteamLib.Core;
using System.Diagnostics;
namespace SteamLib.SteamMobile;
@@ -50,7 +50,7 @@ public static class TimeAligner
var j = JObject.Parse(respStr);
var time = j["response"]!["server_time"]!.Value<long>();
var now = UtcNow - sw.Elapsed;
_timeDifference = (int)(time - now.ToLong());
_timeDifference = (int) (time - now.ToLong());
_aligned = true;
}
finally
@@ -72,7 +72,7 @@ public static class TimeAligner
var j = JObject.Parse(respStr);
var time = j["response"]!["server_time"]!.Value<long>();
var now = UtcNow - sw.Elapsed;
_timeDifference = (int)(time - now.ToLong());
_timeDifference = (int) (time - now.ToLong());
_aligned = true;
}
finally
@@ -60,7 +60,7 @@ public static class EncryptionHelper
break;
}
array[n4] = (byte)time;
array[n4] = (byte) time;
time >>= 8;
n3 = n4;
}
@@ -1,6 +1,6 @@
using Newtonsoft.Json.Linq;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Linq;
using SteamLibForked.Models.SteamIds;
using System.Diagnostics.CodeAnalysis;
namespace SteamLib.Utility.MafileSerialization;
@@ -73,13 +73,13 @@ public class DeserializedMafileInfo
public bool IsActual => Version == MafileSerializer.MAFILE_VERSION;
[MemberNotNullWhen(true, nameof(UnusedProperties))]
public bool HasUnusedProperties => UnusedProperties is { Count: > 0 };
public bool HasUnusedProperties => UnusedProperties is {Count: > 0};
[MemberNotNullWhen(true, nameof(MissingProperties))]
public bool HasMissingProperties => MissingProperties is { Count: > 0 };
public bool HasMissingProperties => MissingProperties is {Count: > 0};
[MemberNotNullWhen(true, nameof(MissingImportantProperties))]
public bool HasMissingImportantProperties => MissingImportantProperties is { Count: > 0 };
public bool HasMissingImportantProperties => MissingImportantProperties is {Count: > 0};
public bool HasSession => SessionResult == DeserializedMafileSessionResult.Valid;
public bool HasIdentificationProperty { get; init; }
@@ -100,7 +100,7 @@ public class DeserializedMafileInfo
isExtended = true;
}
if (isExtended && missingProperties is { Count: > 0 })
if (isExtended && missingProperties is {Count: > 0})
{
var important = missingProperties.Intersect(ImportantProperties).ToList();
if (important.Count > 0) missingImportantProperties = important.ToHashSet();
@@ -29,7 +29,7 @@ public partial class MafileSerializer
var versionToken = GetToken(j, SIGNATURE_PROPERTY_NAME);
unusedProperties.Remove(CREDITS_PROPERTY_NAME);
int? version = null;
if (versionToken is { Type: JTokenType.Integer })
if (versionToken is {Type: JTokenType.Integer})
{
version = versionToken.Value<int>();
}
@@ -1,9 +1,9 @@
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json.Linq;
using SteamLib.Authentication;
using SteamLibForked.Models.Session;
using SteamLibForked.Models.SteamIds;
using System.Security.Cryptography;
using System.Text;
namespace SteamLib.Utility.MafileSerialization;
@@ -17,14 +17,14 @@ public partial class MafileSerializer //SessionData
var refreshToken = GetAuthToken(j, nameof(MobileSessionData.RefreshToken), "refreshtoken", "refresh_token",
"refresh", "OAuthToken");
if (refreshToken is not { Type: SteamAccessTokenType.MobileRefresh })
if (refreshToken is not {Type: SteamAccessTokenType.MobileRefresh})
{
result = DeserializedMafileSessionResult.Invalid;
return null;
}
var accessToken = GetAuthToken(j, "accesstoken", "access_token", "access", "steamLoginSecure");
if (accessToken is not { Type: SteamAccessTokenType.Mobile })
if (accessToken is not {Type: SteamAccessTokenType.Mobile})
{
accessToken = null;
}
@@ -1,6 +1,6 @@
using Newtonsoft.Json.Linq;
using System.Numerics;
using Newtonsoft.Json.Linq;
using SteamLibForked.Models.SteamIds;
using System.Numerics;
namespace SteamLib.Utility.MafileSerialization;
@@ -167,11 +167,11 @@ public partial class MafileSerializer //Utility
{
res = settings.DeserializationOptions.RestrictOverflowSerialNumberRecovery
? 0
: GetFromOverflow((long)bigInt);
: GetFromOverflow((long) bigInt);
}
else if (bigInt > ulong.MinValue && bigInt < ulong.MaxValue) //Valid range
{
res = (ulong)bigInt;
res = (ulong) bigInt;
}
else
{
@@ -192,7 +192,7 @@ public partial class MafileSerializer //Utility
ulong originalValue;
unchecked
{
originalValue = (ulong)overflow + ulong.MaxValue + 1;
originalValue = (ulong) overflow + ulong.MaxValue + 1;
}
return originalValue;
@@ -1,7 +1,7 @@
using Newtonsoft.Json.Linq;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Linq;
using SteamLib.Authentication;
using SteamLibForked.Models.Session;
using System.Diagnostics.CodeAnalysis;
namespace SteamLib.Utility.MafileSerialization;
+2 -2
View File
@@ -1,5 +1,5 @@
using SteamLibForked.Models.SteamIds;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
using SteamLibForked.Models.SteamIds;
namespace SteamLib.Utility;
+3 -3
View File
@@ -1,8 +1,8 @@
using AchiesUtilities.Web.Models;
using System.Net;
using System.Net.Http.Headers;
using AchiesUtilities.Web.Models;
using SteamLib.Authentication;
using SteamLibForked.Abstractions;
using System.Net;
using System.Net.Http.Headers;
namespace SteamLib.Web;
@@ -18,7 +18,7 @@ public class SteamIdToSteam64Converter : JsonConverter<SteamId>
return SteamId.FromSteam64(l);
}
var str = (string)reader.Value!;
var str = (string) reader.Value!;
return new SteamId(SteamId64.Parse(str));
}
}
@@ -33,7 +33,7 @@ public class SteamIdToSteam2Converter : JsonConverter<SteamId>
public override SteamId ReadJson(JsonReader reader, Type objectType, SteamId existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
var str = (string)reader.Value!;
var str = (string) reader.Value!;
return new SteamId(SteamId2.Parse(str));
}
}
@@ -48,7 +48,7 @@ public class SteamIdToSteam3Converter : JsonConverter<SteamId>
public override SteamId ReadJson(JsonReader reader, Type objectType, SteamId existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
var str = (string)reader.Value!;
var str = (string) reader.Value!;
return new SteamId(SteamId3.Parse(str));
}
}
@@ -69,7 +69,7 @@ public class Steam64ToLongConverter : JsonConverter<SteamId64>
return new SteamId64(l);
}
var str = (string)reader.Value!;
var str = (string) reader.Value!;
return SteamId64.Parse(str);
}
}
@@ -84,7 +84,7 @@ public class SteamId2ToStringConverter : JsonConverter<SteamId2>
public override SteamId2 ReadJson(JsonReader reader, Type objectType, SteamId2 existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
var str = (string)reader.Value!;
var str = (string) reader.Value!;
return SteamId2.Parse(str);
}
}
@@ -99,7 +99,7 @@ public class SteamId3ToStringConverter : JsonConverter<SteamId3>
public override SteamId3 ReadJson(JsonReader reader, Type objectType, SteamId3 existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
var str = (string)reader.Value!;
var str = (string) reader.Value!;
return SteamId3.Parse(str);
}
}
@@ -1,9 +1,9 @@
using HtmlAgilityPack;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using JetBrains.Annotations;
using SteamLib.Exceptions.General;
using SteamLib.Models;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
namespace SteamLib.Web.Scrappers.HTML;
@@ -12,9 +12,7 @@ public static class ScriptHeaderScrapper
{
private const string XPATH = "//div[@class='responsive_page_content']/script";
[RegexPattern]
[SuppressMessage("ReSharper", "UseRawString")]
[SuppressMessage("ReSharper", "StringLiteralTypo")]
[RegexPattern] [SuppressMessage("ReSharper", "UseRawString")] [SuppressMessage("ReSharper", "StringLiteralTypo")]
private static readonly string _regexTip =
@"g_sessionID = ""(?<g_sessionID>.*)"";"
+ @"\s*g_steamID = (?<g_steamID>.*);";
@@ -78,7 +78,7 @@ public static class MobileConfirmationScrapper
ConfirmationType.MarketSellTransaction => GetMarketConfirmation(json),
ConfirmationType.RegisterApiKey => GetRegisterApiKeyConfirmation(json),
ConfirmationType.Purchase => GetPurchaseConfirmation(json),
_ => new Confirmation(json.Id, json.Nonce, (int)json.Type, json.CreatorId, json.Type, json.TypeName)
_ => new Confirmation(json.Id, json.Nonce, (int) json.Type, json.CreatorId, json.Type, json.TypeName)
{
Time = json.CreationTime.ToLocalDateTime()
}