SearchResultView and DownloadView implemented;

Ignore whitespaces and special chars when looking for games;
This commit is contained in:
Jeddunk 2020-12-28 15:27:37 +01:00
parent aada82693d
commit 73baa27245
26 changed files with 783 additions and 642 deletions

View file

@ -0,0 +1,87 @@
using System.Threading.Tasks;
using auto_creamapi.Messenger;
using auto_creamapi.Services;
using auto_creamapi.Utils;
using MvvmCross.Logging;
using MvvmCross.Navigation;
using MvvmCross.Plugin.Messenger;
using MvvmCross.ViewModels;
namespace auto_creamapi.ViewModels
{
public class DownloadViewModel : MvxNavigationViewModel
{
private readonly IDownloadCreamApiService _download;
private readonly IMvxNavigationService _navigationService;
private readonly MvxSubscriptionToken _token;
private string _filename;
private string _info;
private double _progress;
public DownloadViewModel(IMvxLogProvider logProvider, IMvxNavigationService navigationService,
IDownloadCreamApiService download, IMvxMessenger messenger) : base(logProvider, navigationService)
{
_navigationService = navigationService;
_download = download;
_token = messenger.Subscribe<ProgressMessage>(OnProgressMessage);
MyLogger.Log.Debug(messenger.CountSubscriptionsFor<ProgressMessage>().ToString());
}
public string InfoLabel
{
get => _info;
set
{
_info = value;
RaisePropertyChanged(() => InfoLabel);
}
}
public string FilenameLabel
{
get => _filename;
set
{
_filename = value;
RaisePropertyChanged(() => FilenameLabel);
}
}
public double Progress
{
get => _progress;
set
{
_progress = value;
RaisePropertyChanged(() => Progress);
RaisePropertyChanged(() => ProgressPercent);
}
}
public string ProgressPercent => _progress.ToString("P2");
public override async Task Initialize()
{
await base.Initialize();
InfoLabel = "Please wait...";
FilenameLabel = "";
Progress = 0.0;
var download = _download.Download(Secrets.ForumUsername, Secrets.ForumPassword);
var filename = await download;
/*var extract = _download.Extract(filename);
await extract;*/
await Task.Run(() => _download.Extract(filename));
_token.Dispose();
await _navigationService.Close(this);
}
private void OnProgressMessage(ProgressMessage obj)
{
//MyLogger.Log.Debug($"{obj.Filename}: {obj.BytesTransferred}");
InfoLabel = obj.Info;
FilenameLabel = obj.Filename;
Progress = obj.PercentComplete;
}
}
}

View file

@ -3,218 +3,68 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Threading;
using auto_creamapi.Models;
using auto_creamapi.Services;
using auto_creamapi.Utils;
using auto_creamapi.Views;
using Microsoft.Win32;
using MvvmCross.Commands;
using MvvmCross.Navigation;
using MvvmCross.ViewModels;
namespace auto_creamapi.ViewModels
{
public class MainViewModel : MvxViewModel
{
private const string DefaultLanguageSelection = "english";
private readonly ICacheService _cache;
private readonly ICreamConfigService _config;
private readonly ICreamDllService _dll;
private readonly IDownloadCreamApiService _download;
private bool _mainWindowEnabled;
private string _dllPath;
private string _gameName;
private readonly IMvxNavigationService _navigationService;
private int _appId;
private string _lang;
private bool _offline;
private bool _extraprotection;
private bool _unlockall;
private bool _useSteamDb;
private bool _configExists;
private ObservableCollection<SteamApp> _dlcs;
private bool _dllApplied;
private bool _configExists;
private string _status;
private string _dllPath;
private bool _extraprotection;
private string _gameName;
private string _lang;
private ObservableCollection<string> _languages;
private const string DefaultLanguageSelection = "english";
private const string DlcRegexPattern = @"(?<id>.*) *= *(?<name>.*)";
//private readonly IDownloadCreamApiService _download;
private bool _mainWindowEnabled;
private bool _offline;
private string _status;
private bool _unlockall;
private bool _useSteamDb;
//private const string DlcRegexPattern = @"(?<id>.*) *= *(?<name>.*)";
public MainViewModel(ICacheService cache, ICreamConfigService config, ICreamDllService dll,
IDownloadCreamApiService download)
IMvxNavigationService navigationService)
{
_navigationService = navigationService;
_cache = cache;
_config = config;
_dll = dll;
_download = download;
}
public override async Task Initialize()
{
await base.Initialize();
Languages = new ObservableCollection<string>(_cache.Languages);
ResetForm();
_download.Initialize();
_dll.Initialize();
Lang = DefaultLanguageSelection;
UseSteamDb = true;
MainWindowEnabled = true;
Status = "Ready.";
//_download = download;
}
// // COMMANDS // //
public IMvxCommand OpenFileCommand => new MvxCommand(OpenFile);
private void OpenFile()
{
Status = "Waiting for file...";
var dialog = new OpenFileDialog
{
Filter = "SteamAPI DLL|steam_api.dll;steam_api64.dll|" +
"All files (*.*)|*.*",
Multiselect = false,
Title = "Select SteamAPI DLL..."
};
if (dialog.ShowDialog() == true)
{
var filePath = dialog.FileName;
DllPath = filePath;
var dirPath = Path.GetDirectoryName(filePath);
if (dirPath != null)
{
_config.ReadFile(Path.Combine(dirPath, "cream_api.ini"));
ResetForm();
_dll.TargetPath = dirPath;
_dll.CheckIfDllExistsAtTarget();
CheckExistence();
Status = "Ready.";
}
}
}
public IMvxCommand SearchCommand => new MvxCommand(Search);
private void Search()
{
var app = _cache.GetAppByName(GameName);
if (app != null)
{
GameName = app.Name;
AppId = app.AppId;
}
/*else
{
var listOfAppsByName = _cache.GetListOfAppsByName(GameName);
var searchWindow = new SearchResultWindow(listOfAppsByName);
searchWindow.Show();
}*/
}
public IMvxCommand SearchCommand => new MvxAsyncCommand(async () => await Search()); //Command(Search);
public IMvxCommand GetListOfDlcCommand => new MvxAsyncCommand(GetListOfDlc);
private async Task GetListOfDlc()
{
Status = "Trying to get DLC...";
if (AppId > 0)
{
var app = new SteamApp() {AppId = AppId, Name = GameName};
var task = _cache.GetListOfDlc(app, UseSteamDb);
MainWindowEnabled = false;
var listOfDlc = await task;
var result = "";
if (task.IsCompletedSuccessfully)
{
listOfDlc.Sort((app1, app2) => app1.AppId.CompareTo(app2.AppId));
listOfDlc.ForEach(x => result += $"{x.AppId}={x.Name}\n");
Dlcs = result;
Status = $"Got DLC for AppID {AppId}";
}
else
{
Status = $"Could not get DLC for AppID {AppId}";
}
MainWindowEnabled = true;
}
else
{
Status = $"Could not get DLC for AppID {AppId}";
MyLogger.Log.Error($"GetListOfDlc: Invalid AppID {AppId}");
}
}
public IMvxCommand SaveCommand => new MvxCommand(Save);
private void Save()
{
Status = "Saving...";
_config.SetConfigData(
AppId,
Lang,
Unlockall,
Extraprotection,
Offline,
Dlcs
);
_config.SaveFile();
_dll.Save();
CheckExistence();
Status = "Saving successful.";
}
public IMvxCommand ResetFormCommand => new MvxCommand(ResetForm);
private void ResetForm()
{
AppId = _config.Config.AppId;
Lang = _config.Config.Language;
Unlockall = _config.Config.UnlockAll;
Extraprotection = _config.Config.ExtraProtection;
Offline = _config.Config.ForceOffline;
var configDlcList = _config.Config.DlcList;
var result = "";
foreach (var x in configDlcList)
{
result += $"{x.AppId}={x.Name}\n";
}
Dlcs = result;
}
public IMvxCommand GoToForumThreadCommand => new MvxCommand(GoToForumThread);
private void GoToForumThread()
{
Status = "Opening URL...";
if (AppId > 0)
{
var searchTerm = AppId; //$"{GameName.Replace(" ", "+")}+{appId}";
var destinationUrl =
"https://cs.rin.ru/forum/search.php?keywords=" +
searchTerm +
"&terms=any&fid[]=10&sf=firstpost&sr=topics&submit=Search";
var uri = new Uri(destinationUrl);
var process = new ProcessStartInfo(uri.AbsoluteUri)
{
UseShellExecute = true
};
Process.Start(process);
}
else
{
MyLogger.Log.Error($"OpenURL: Invalid AppID {AppId}");
Status = $"Could not open URL: Invalid AppID {AppId}";
}
}
private void CheckExistence()
{
DllApplied = _dll.CreamApiApplied();
ConfigExists = _config.ConfigExists();
}
// // ATTRIBUTES // //
public bool MainWindowEnabled
@ -259,12 +109,6 @@ namespace auto_creamapi.ViewModels
}
}
private void SetNameById()
{
var appById = _cache.GetAppById(_appId);
GameName = appById != null ? appById.Name : "";
}
public string Lang
{
get => _lang;
@ -316,53 +160,14 @@ namespace auto_creamapi.ViewModels
}
}
/*public List<SteamApp> Dlcs
public ObservableCollection<SteamApp> Dlcs
{
get => _dlcs;
set
{
_dlcs = value;
RaisePropertyChanged(Dlcs);
MyLogger.Log.Debug($"Dlcs: {value}");
RaisePropertyChanged(() => Dlcs);
}
}*/
public string Dlcs
{
get => DlcListToString(_dlcs);
set
{
_dlcs = StringToDlcList(value);
RaisePropertyChanged();
//MyLogger.Log.Debug($"Dlcs: {DlcListToString(_dlcs)}");
}
}
private static ObservableCollection<SteamApp> StringToDlcList(string value)
{
var result = new List<SteamApp>();
var expression = new Regex(@"(?<id>.*) *= *(?<name>.*)");
using var reader = new StringReader(value);
string line;
while ((line = reader.ReadLine()) != null)
{
var match = expression.Match(line);
if (match.Success)
{
result.Add(new SteamApp
{
AppId = int.Parse(match.Groups["id"].Value),
Name = match.Groups["name"].Value
});
}
}
return new ObservableCollection<SteamApp>(result);
}
private static string DlcListToString(IEnumerable<SteamApp> value)
{
return value.Aggregate("", (current, steamApp) => current + $"{steamApp}\n");
}
public bool DllApplied
@ -404,5 +209,179 @@ namespace auto_creamapi.ViewModels
RaisePropertyChanged(() => Languages);
}
}
public override async Task Initialize()
{
_config.Initialize();
/*await base.Initialize();
await _cache.Initialize();
if (!File.Exists("steam_api.dll") | !File.Exists("steam_api64.dll"))
await _navigationService.Navigate<DownloadViewModel>();
await _dll.Initialize();*/
var tasks = new List<Task> {base.Initialize(), _cache.Initialize()};
if (!File.Exists("steam_api.dll") | !File.Exists("steam_api64.dll"))
tasks.Add(_navigationService.Navigate<DownloadViewModel>());
tasks.Add(_dll.Initialize());
await Task.WhenAll(tasks);
Languages = new ObservableCollection<string>(_cache.Languages);
ResetForm();
Lang = DefaultLanguageSelection;
UseSteamDb = true;
MainWindowEnabled = true;
Status = "Ready.";
}
private void OpenFile()
{
Status = "Waiting for file...";
var dialog = new OpenFileDialog
{
Filter = "SteamAPI DLL|steam_api.dll;steam_api64.dll|" +
"All files (*.*)|*.*",
Multiselect = false,
Title = "Select SteamAPI DLL..."
};
if (dialog.ShowDialog() == true)
{
var filePath = dialog.FileName;
DllPath = filePath;
var dirPath = Path.GetDirectoryName(filePath);
if (dirPath != null)
{
_config.ReadFile(Path.Combine(dirPath, "cream_api.ini"));
ResetForm();
_dll.TargetPath = dirPath;
_dll.CheckIfDllExistsAtTarget();
CheckExistence();
Status = "Ready.";
}
}
else
{
Status = "File selection canceled.";
}
}
private async Task Search()
{
if (!string.IsNullOrEmpty(GameName))
{
var app = _cache.GetAppByName(GameName);
if (app != null)
{
GameName = app.Name;
AppId = app.AppId;
}
else
{
var navigate = _navigationService.Navigate<SearchResultViewModel, IEnumerable<SteamApp>, SteamApp>(
_cache.GetListOfAppsByName(GameName));
await navigate;
var navigateResult = navigate.Result;
if (navigateResult != null)
{
GameName = navigateResult.Name;
AppId = navigateResult.AppId;
}
}
}
else
{
MyLogger.Log.Warning("Empty game name, cannot initiate search!");
}
}
private async Task GetListOfDlc()
{
Status = "Trying to get DLC...";
if (AppId > 0)
{
var app = new SteamApp {AppId = AppId, Name = GameName};
var task = _cache.GetListOfDlc(app, UseSteamDb);
MainWindowEnabled = false;
var listOfDlc = await task;
if (task.IsCompletedSuccessfully)
{
listOfDlc.Sort((app1, app2) => app1.AppId.CompareTo(app2.AppId));
Dlcs = new ObservableCollection<SteamApp>(listOfDlc);
Status = $"Got DLC for AppID {AppId}";
}
else
{
Status = $"Could not get DLC for AppID {AppId}";
}
MainWindowEnabled = true;
}
else
{
Status = $"Could not get DLC for AppID {AppId}";
MyLogger.Log.Error($"GetListOfDlc: Invalid AppID {AppId}");
}
}
private void Save()
{
Status = "Saving...";
_config.SetConfigData(
AppId,
Lang,
Unlockall,
Extraprotection,
Offline,
Dlcs
);
_config.SaveFile();
_dll.Save();
CheckExistence();
Status = "Saving successful.";
}
private void ResetForm()
{
AppId = _config.Config.AppId;
Lang = _config.Config.Language;
Unlockall = _config.Config.UnlockAll;
Extraprotection = _config.Config.ExtraProtection;
Offline = _config.Config.ForceOffline;
Dlcs = new ObservableCollection<SteamApp>(_config.Config.DlcList);
Status = "Changes have been reset.";
}
private void GoToForumThread()
{
Status = "Opening URL...";
if (AppId > 0)
{
var searchTerm = AppId; //$"{GameName.Replace(" ", "+")}+{appId}";
var destinationUrl =
"https://cs.rin.ru/forum/search.php?keywords=" +
searchTerm +
"&terms=any&fid[]=10&sf=firstpost&sr=topics&submit=Search";
var uri = new Uri(destinationUrl);
var process = new ProcessStartInfo(uri.AbsoluteUri)
{
UseShellExecute = true
};
Process.Start(process);
}
else
{
MyLogger.Log.Error($"OpenURL: Invalid AppID {AppId}");
Status = $"Could not open URL: Invalid AppID {AppId}";
}
}
private void CheckExistence()
{
DllApplied = _dll.CreamApiApplied();
ConfigExists = _config.ConfigExists();
}
private void SetNameById()
{
var appById = _cache.GetAppById(_appId);
GameName = appById != null ? appById.Name : "";
}
}
}

View file

@ -0,0 +1,80 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using auto_creamapi.Models;
using auto_creamapi.Utils;
using MvvmCross.Commands;
using MvvmCross.Logging;
using MvvmCross.Navigation;
using MvvmCross.ViewModels;
namespace auto_creamapi.ViewModels
{
public class SearchResultViewModel : MvxNavigationViewModel<IEnumerable<SteamApp>>,
IMvxViewModel<IEnumerable<SteamApp>, SteamApp>
{
private readonly IMvxNavigationService _navigationService;
private IEnumerable<SteamApp> _steamApps;
/*public override async Task Initialize()
{
await base.Initialize();
}*/
public SearchResultViewModel(IMvxLogProvider logProvider, IMvxNavigationService navigationService) : base(
logProvider, navigationService)
{
_navigationService = navigationService;
}
public IEnumerable<SteamApp> Apps
{
get => _steamApps;
set
{
_steamApps = value;
RaisePropertyChanged(() => Apps);
}
}
public SteamApp Selected
{
get;
set;
//RaisePropertyChanged(Selected);
}
public IMvxCommand SaveCommand => new MvxAsyncCommand(Save);
public IMvxCommand CloseCommand => new MvxCommand(Close);
public override void Prepare(IEnumerable<SteamApp> parameter)
{
Apps = parameter;
}
public TaskCompletionSource<object> CloseCompletionSource { get; set; }
public override void ViewDestroy(bool viewFinishing = true)
{
if (viewFinishing && CloseCompletionSource != null && !CloseCompletionSource.Task.IsCompleted &&
!CloseCompletionSource.Task.IsFaulted)
CloseCompletionSource?.TrySetCanceled();
base.ViewDestroy(viewFinishing);
}
private async Task Save()
{
if (Selected != null)
{
MyLogger.Log.Information($"Successfully got app {Selected}");
await _navigationService.Close(this, Selected);
}
}
private void Close()
{
//throw new System.NotImplementedException();
_navigationService.Close(this);
}
}
}