Reimplemented using MVVMCross (SearchResultWindow & DownloadWindow WIP)

This commit is contained in:
Jeddunk 2020-12-25 16:49:51 +01:00
parent c7308cfc29
commit aada82693d
33 changed files with 1609 additions and 1758 deletions

View file

@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using auto_creamapi.Models;
using auto_creamapi.Utils;
using NinjaNye.SearchExtensions;
using SteamStorefrontAPI;
namespace auto_creamapi.Services
{
public interface ICacheService
{
public List<string> Languages { get; }
public void UpdateCache();
public IEnumerable<SteamApp> GetListOfAppsByName(string name);
public SteamApp GetAppByName(string name);
public SteamApp GetAppById(int appid);
public Task<List<SteamApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb);
}
public class CacheService : ICacheService
{
private const string CachePath = "steamapps.json";
private const string SteamUri = "https://api.steampowered.com/ISteamApps/GetAppList/v2/";
private const string UserAgent =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/87.0.4280.88 Safari/537.36";
private List<SteamApp> _cache = new List<SteamApp>();
private readonly List<string> _languages = new List<string>(new[]
{
"arabic",
"bulgarian",
"schinese",
"tchinese",
"czech",
"danish",
"dutch",
"english",
"finnish",
"french",
"german",
"greek",
"hungarian",
"italian",
"japanese",
"koreana",
"norwegian",
"polish",
"portuguese",
"brazilian",
"romanian",
"russian",
"spanish",
"latam",
"swedish",
"thai",
"turkish",
"ukrainian",
"vietnamese"
});
/*private static readonly Lazy<CacheService> Lazy =
new Lazy<CacheService>(() => new CacheService());
public static CacheService Instance => Lazy.Value;*/
public CacheService()
{
Languages = _languages;
UpdateCache();
}
public List<string> Languages { get; }
public void UpdateCache()
{
MyLogger.Log.Information("Updating cache...");
var updateNeeded = DateTime.Now.Subtract(File.GetLastWriteTimeUtc(CachePath)).TotalDays >= 1;
string cacheString;
if (updateNeeded)
{
MyLogger.Log.Information("Getting content from API...");
var client = new HttpClient();
var httpCall = client.GetAsync(SteamUri);
var response = httpCall.Result;
var readAsStringAsync = response.Content.ReadAsStringAsync();
var responseBody = readAsStringAsync.Result;
MyLogger.Log.Information("Got content from API successfully. Writing to file...");
//var writeAllTextAsync = File.WriteAllTextAsync(CachePath, responseBody, Encoding.UTF8);
//writeAllTextAsync.RunSynchronously();
File.WriteAllText(CachePath, responseBody, Encoding.UTF8);
cacheString = responseBody;
MyLogger.Log.Information("Cache written to file successfully.");
}
else
{
MyLogger.Log.Information("Cache already up to date!");
cacheString = File.ReadAllText(CachePath);
}
var steamApps = JsonSerializer.Deserialize<SteamApps>(cacheString);
_cache = steamApps.AppList.Apps;
MyLogger.Log.Information("Loaded cache into memory!");
}
public IEnumerable<SteamApp> GetListOfAppsByName(string name)
{
var listOfAppsByName = _cache.Search(x => x.Name)
.SetCulture(StringComparison.OrdinalIgnoreCase)
.ContainingAll(name.Split(' '));
return listOfAppsByName;
}
public SteamApp GetAppByName(string name)
{
MyLogger.Log.Information($"Trying to get app {name}");
var app = _cache.Find(x => x.Name.ToLower().Equals(name.ToLower()));
if (app != null) MyLogger.Log.Information($"Successfully got app {app}");
return app;
}
public SteamApp GetAppById(int appid)
{
MyLogger.Log.Information($"Trying to get app with ID {appid}");
var app = _cache.Find(x => x.AppId.Equals(appid));
if (app != null) MyLogger.Log.Information($"Successfully got app {app}");
return app;
}
public async Task<List<SteamApp>> GetListOfDlc(SteamApp steamApp, bool useSteamDb)
{
MyLogger.Log.Information("Get DLC");
var dlcList = new List<SteamApp>();
if (steamApp != null)
{
var task = AppDetails.GetAsync(steamApp.AppId);
var steamAppDetails = await task;
steamAppDetails?.DLC.ForEach(x =>
{
var result = _cache.Find(y => y.AppId.Equals(x)) ??
new SteamApp {AppId = x, Name = $"Unknown DLC {x}"};
dlcList.Add(result);
});
dlcList.ForEach(x => MyLogger.Log.Debug($"{x.AppId}={x.Name}"));
MyLogger.Log.Information("Got DLC successfully...");
// Get DLC from SteamDB
// Get Cloudflare cookie
// Scrape and parse HTML page
// Add missing to DLC list
if (useSteamDb)
{
var steamDbUri = new Uri($"https://steamdb.info/app/{steamApp.AppId}/dlc/");
/* var handler = new ClearanceHandler();
var client = new HttpClient(handler);
var content = client.GetStringAsync(steamDbUri).Result;
MyLogger.Log.Debug(content); */
var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
MyLogger.Log.Information("Get SteamDB App");
var httpCall = client.GetAsync(steamDbUri);
var response = await httpCall;
MyLogger.Log.Debug(httpCall.Status.ToString());
MyLogger.Log.Debug(response.EnsureSuccessStatusCode().ToString());
var readAsStringAsync = response.Content.ReadAsStringAsync();
var responseBody = await readAsStringAsync;
MyLogger.Log.Debug(readAsStringAsync.Status.ToString());
var parser = new HtmlParser();
var doc = parser.ParseDocument(responseBody);
// Console.WriteLine(doc.DocumentElement.OuterHtml);
var query1 = doc.QuerySelector("#dlc");
if (query1 != null)
{
var query2 = query1.QuerySelectorAll(".app");
foreach (var element in query2)
{
var dlcId = element.GetAttribute("data-appid");
var dlcName = $"Unknown DLC {dlcId}";
var query3 = element.QuerySelectorAll("td");
if (query3 != null)
{
dlcName = query3[1].Text().Replace("\n", "").Trim();
}
var dlcApp = new SteamApp {AppId = Convert.ToInt32(dlcId), Name = dlcName};
var i = dlcList.FindIndex(x => x.CompareId(dlcApp));
if (i > -1)
{
if (dlcList[i].Name.Contains("Unknown DLC")) dlcList[i] = dlcApp;
}
else
{
dlcList.Add(dlcApp);
}
}
dlcList.ForEach(x => MyLogger.Log.Debug($"{x.AppId}={x.Name}"));
MyLogger.Log.Information("Got DLC from SteamDB successfully...");
}
else
{
MyLogger.Log.Error("Could not get DLC from SteamDB1");
}
}
}
else
{
MyLogger.Log.Error($"Could not get DLC: Invalid Steam App");
}
return dlcList;
}
}
}

View file

@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using auto_creamapi.Models;
using auto_creamapi.Utils;
using IniParser;
using IniParser.Model;
namespace auto_creamapi.Services
{
public interface ICreamConfigService
{
public CreamConfig Config { get; }
public void ReadFile(string configFilePath);
public void SaveFile();
public void SetConfigData(int appId,
string language,
bool unlockAll,
bool extraProtection,
bool forceOffline,
string dlcList);
public void SetConfigData(int appId,
string language,
bool unlockAll,
bool extraProtection,
bool forceOffline,
List<SteamApp> dlcList);
public bool ConfigExists();
}
public class CreamConfigService : ICreamConfigService
{
public CreamConfig Config { get; }
private string _configFilePath;
public CreamConfigService()
{
Config = new CreamConfig();
ResetConfigData();
}
public void ReadFile(string configFilePath)
{
_configFilePath = configFilePath;
if (File.Exists(configFilePath))
{
MyLogger.Log.Information($"Config file found @ {configFilePath}, parsing...");
var parser = new FileIniDataParser();
var data = parser.ReadFile(_configFilePath, Encoding.UTF8);
ResetConfigData(); // clear previous config data
Config.AppId = Convert.ToInt32(data["steam"]["appid"]);
Config.Language = data["steam"]["language"];
Config.UnlockAll = Convert.ToBoolean(data["steam"]["unlockall"]);
Config.ExtraProtection = Convert.ToBoolean(data["steam"]["extraprotection"]);
Config.ForceOffline = Convert.ToBoolean(data["steam"]["forceoffline"]);
var dlcCollection = data["dlc"];
foreach (var item in dlcCollection)
{
//Config.DlcList.Add(int.Parse(item.KeyName), item.Value);
Config.DlcList.Add(new SteamApp{AppId = int.Parse(item.KeyName), Name = item.Value});
}
}
else
{
MyLogger.Log.Information($"Config file does not exist @ {configFilePath}, skipping...");
ResetConfigData();
}
}
public void SaveFile()
{
var parser = new FileIniDataParser();
var data = new IniData();
data["steam"]["appid"] = Config.AppId.ToString();
data["steam"]["language"] = Config.Language;
data["steam"]["unlockall"] = Config.UnlockAll.ToString();
data["steam"]["extraprotection"] = Config.ExtraProtection.ToString();
data["steam"]["forceoffline"] = Config.ForceOffline.ToString();
data.Sections.AddSection("dlc");
Config.DlcList.ForEach(x => data["dlc"].AddKey(x.AppId.ToString(), x.Name));
/*foreach (var steamApp in Config.DlcList)
{
data["dlc"].AddKey(key.ToString(), value);
}*/
parser.WriteFile(_configFilePath, data, Encoding.UTF8);
}
private void ResetConfigData()
{
Config.AppId = -1;
Config.Language = "";
Config.UnlockAll = false;
Config.ExtraProtection = false;
Config.ForceOffline = false;
Config.DlcList.Clear();
}
public void SetConfigData(int appId,
string language,
bool unlockAll,
bool extraProtection,
bool forceOffline,
string dlcList)
{
Config.AppId = appId;
Config.Language = language;
Config.UnlockAll = unlockAll;
Config.ExtraProtection = extraProtection;
Config.ForceOffline = forceOffline;
SetDlcFromString(dlcList);
}
public void SetConfigData(int appId,
string language,
bool unlockAll,
bool extraProtection,
bool forceOffline,
List<SteamApp> dlcList)
{
Config.AppId = appId;
Config.Language = language;
Config.UnlockAll = unlockAll;
Config.ExtraProtection = extraProtection;
Config.ForceOffline = forceOffline;
Config.DlcList = dlcList;
}
private void SetDlcFromString(string dlcList)
{
Config.DlcList.Clear();
var expression = new Regex(@"(?<id>.*) *= *(?<name>.*)");
using var reader = new StringReader(dlcList);
string line;
while ((line = reader.ReadLine()) != null)
{
var match = expression.Match(line);
if (match.Success)
{
Config.DlcList.Add(
new SteamApp{AppId = int.Parse(match.Groups["id"].Value), Name = match.Groups["name"].Value});
}
}
}
/*private void SetDlcFromAppList(List<SteamApp> dlcList)
{
Config.DlcList.Clear();
dlcList.ForEach(x => Config.DlcList.Add(x.AppId, x.Name));
}*/
public override string ToString()
{
var str = $"INI file: {_configFilePath}, " +
$"AppID: {Config.AppId}, " +
$"Language: {Config.Language}, " +
$"UnlockAll: {Config.UnlockAll}, " +
$"ExtraProtection: {Config.ExtraProtection}, " +
$"ForceOffline: {Config.ForceOffline}, " +
$"DLC ({Config.DlcList.Count}):\n[\n";
if (Config.DlcList.Count > 0)
{
str = Config.DlcList.Aggregate(str, (current, x) => current + $" {x.AppId}={x.Name},\n");
/*foreach (var (key, value) in Config.DlcList)
{
str += $" {key}={value},\n";
}*/
}
str += "]";
return str;
}
public bool ConfigExists()
{
return File.Exists(_configFilePath);
}
}
}

View file

@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;
using auto_creamapi.Models;
using auto_creamapi.Utils;
namespace auto_creamapi.Services
{
public interface ICreamDllService
{
public string TargetPath { get; set; }
public void Initialize();
//public Task InitializeAsync();
public void Save();
public void CheckIfDllExistsAtTarget();
public bool CreamApiApplied();
}
public class CreamDllService : ICreamDllService
{
private readonly IDownloadCreamApiService _downloadService;
public string TargetPath { get; set; }
private readonly Dictionary<string, CreamDll> _creamDlls = new Dictionary<string, CreamDll>();
private static readonly string HashPath = Path.Combine(Directory.GetCurrentDirectory(), "cream_api.md5");
private const string X86Arch = "x86";
private const string X64Arch = "x64";
private bool _x86Exists;
private bool _x64Exists;
public CreamDllService(IDownloadCreamApiService downloadService)
{
_downloadService = downloadService;
}
public Task InitializeAsync()
{
return Task.Run(Initialize);
}
public void Initialize()
{
MyLogger.Log.Debug("CreamDllService: Initialize begin");
_creamDlls.Add(X86Arch, new CreamDll("steam_api.dll", "steam_api_o.dll"));
_creamDlls.Add(X64Arch, new CreamDll("steam_api64.dll", "steam_api64_o.dll"));
if (!File.Exists(HashPath))
{
MyLogger.Log.Information("Writing md5sum file...");
File.WriteAllLines(HashPath, new[]
{
$"{_creamDlls[X86Arch].Hash} {_creamDlls[X86Arch].Filename}",
$"{_creamDlls[X64Arch].Hash} {_creamDlls[X64Arch].Filename}"
});
}
MyLogger.Log.Debug("CreamDllService: Initialize end");
}
public void Save()
{
if (_x86Exists) CopyDll(X86Arch);
if (_x64Exists) CopyDll(X64Arch);
}
private void CopyDll(string arch)
{
var sourceSteamApiDll = _creamDlls[arch].Filename;
var targetSteamApiDll = Path.Combine(TargetPath, _creamDlls[arch].Filename);
var targetSteamApiOrigDll = Path.Combine(TargetPath, _creamDlls[arch].OrigFilename);
var targetSteamApiDllBackup = Path.Combine(TargetPath, $"{_creamDlls[arch].Filename}.backup");
MyLogger.Log.Information($"Setting up CreamAPI DLL @ {TargetPath} (arch :{arch})");
// Create backup of steam_api.dll
File.Copy(targetSteamApiDll, targetSteamApiDllBackup, true);
// Check if steam_api_o.dll already exists
// If missing rename original file
if (!File.Exists(targetSteamApiOrigDll))
File.Move(targetSteamApiDll, targetSteamApiOrigDll, true);
// Copy creamapi dll
File.Copy(sourceSteamApiDll, targetSteamApiDll, true);
}
public void CheckIfDllExistsAtTarget()
{
var x86file = Path.Combine(TargetPath, "steam_api.dll");
var x64file = Path.Combine(TargetPath, "steam_api64.dll");
_x86Exists = File.Exists(x86file);
_x64Exists = File.Exists(x64file);
if (_x86Exists) MyLogger.Log.Information($"x86 SteamAPI DLL found: {x86file}");
if (_x64Exists) MyLogger.Log.Information($"x64 SteamAPI DLL found: {x64file}");
}
public bool CreamApiApplied(string arch)
{
bool a = File.Exists(Path.Combine(TargetPath, _creamDlls[arch].OrigFilename));
bool b = GetHash(Path.Combine(TargetPath, _creamDlls[arch].Filename)).Equals(_creamDlls[arch].Hash);
return a & b;
}
public bool CreamApiApplied()
{
bool a = CreamApiApplied("x86");
bool b = CreamApiApplied("x64");
return a | b;
}
private string GetHash(string filename)
{
if (File.Exists(filename))
{
using var md5 = MD5.Create();
using var stream = File.OpenRead(filename);
return BitConverter
.ToString(md5.ComputeHash(stream))
.Replace("-", string.Empty);
}
else
{
return "";
}
}
}
}

View file

@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Threading;
using auto_creamapi.Utils;
using HttpProgress;
using SharpCompress.Archives;
using SharpCompress.Common;
using SharpCompress.Readers;
namespace auto_creamapi.Services
{
public interface IDownloadCreamApiService
{
public void Initialize();
// public Task InitializeAsync();
public Task DownloadAndExtract(string username, string password);
}
public class DownloadCreamApiService : IDownloadCreamApiService
{
private const string ArchivePassword = "cs.rin.ru";
private static string _filename;
//private static DownloadWindow _wnd;
public DownloadCreamApiService()
{
}
public void Initialize()
{
MyLogger.Log.Debug("DownloadCreamApiService: Initialize begin");
if (File.Exists("steam_api.dll") && File.Exists("steam_api64.dll"))
{
MyLogger.Log.Information("Skipping download...");
}
else
{
MyLogger.Log.Information("Missing files, trying to download...");
DownloadAndExtract(Secrets.ForumUsername, Secrets.ForumPassword).Start();
}
//await creamDllService.InitializeAsync();
MyLogger.Log.Debug("DownloadCreamApiService: Initialize end");
}
public async Task InitializeAsync()
{
MyLogger.Log.Debug("DownloadCreamApiService: Initialize begin");
if (File.Exists("steam_api.dll") && File.Exists("steam_api64.dll"))
{
MyLogger.Log.Information("Skipping download...");
}
else
{
MyLogger.Log.Information("Missing files, trying to download...");
var downloadAndExtract = DownloadAndExtract(Secrets.ForumUsername, Secrets.ForumPassword);
await downloadAndExtract;
downloadAndExtract.Wait();
}
//await creamDllService.InitializeAsync();
MyLogger.Log.Debug("DownloadCreamApiService: Initialize end");
}
public async Task DownloadAndExtract(string username, string password)
{
MyLogger.Log.Debug("DownloadAndExtract");
//_wnd = new DownloadWindow();
//_wnd.Show();
var download = Download(username, password);
await download;
download.Wait();
/*var extract = Extract();
await extract;
extract.Wait();*/
var extract = Task.Run(Extract);
await extract;
extract.Wait();
//_wnd.Close();
}
private static async Task Download(string username, string password)
{
MyLogger.Log.Debug("Download");
var container = new CookieContainer();
var handler = new HttpClientHandler {CookieContainer = container};
var client = new HttpClient(handler);
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("redirect", "./ucp.php?mode=login"),
new KeyValuePair<string, string>("login", "login")
});
MyLogger.Log.Debug("Download: post login");
var response1 = await client.PostAsync("https://cs.rin.ru/forum/ucp.php?mode=login", formContent);
MyLogger.Log.Debug($"Login Status Code: {response1.EnsureSuccessStatusCode().StatusCode.ToString()}");
var cookie = container.GetCookies(new Uri("https://cs.rin.ru/forum/ucp.php?mode=login"))
.FirstOrDefault(c => c.Name.Contains("_sid"));
MyLogger.Log.Debug($"Login Cookie: {cookie}");
var response2 = await client.GetAsync("https://cs.rin.ru/forum/viewtopic.php?t=70576");
MyLogger.Log.Debug(
$"Download Page Status Code: {response2.EnsureSuccessStatusCode().StatusCode.ToString()}");
var content = response2.Content.ReadAsStringAsync();
var contentResult = await content;
var expression =
new Regex(".*<a href=\"\\.(?<url>\\/download\\/file\\.php\\?id=.*)\">(?<filename>.*)<\\/a>.*");
using var reader = new StringReader(contentResult);
string line;
var archiveFileList = new Dictionary<string, string>();
while ((line = await reader.ReadLineAsync()) != null)
{
var match = expression.Match(line);
// ReSharper disable once InvertIf
if (match.Success)
{
archiveFileList.Add(match.Groups["filename"].Value,
$"https://cs.rin.ru/forum{match.Groups["url"].Value}");
MyLogger.Log.Debug(archiveFileList.LastOrDefault().Key);
}
}
/*foreach (var (filename, url) in archiveFileList)
{
MyLogger.Log.Information($"Downloading file: {filename}");
var fileResponse = await client.GetAsync(url);
var download = fileResponse.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync(filename, await download);
}*/
MyLogger.Log.Debug("Choosing first element from list...");
var (filename, url) = archiveFileList.FirstOrDefault();
_filename = filename;
if (File.Exists(_filename))
{
MyLogger.Log.Information($"{_filename} already exists, skipping download...");
return;
}
MyLogger.Log.Information("Start download...");
/*await _wnd.FilenameLabel.Dispatcher.InvokeAsync(
() => _wnd.FilenameLabel.Content = _filename, DispatcherPriority.Background);
await _wnd.InfoLabel.Dispatcher.InvokeAsync(
() => _wnd.InfoLabel.Content = "Downloading...", DispatcherPriority.Background);*/
/*var fileResponse = await client.GetAsync(url);
var download = fileResponse.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync(filename, await download);
MyLogger.Log.Information($"Download success? {download.IsCompletedSuccessfully}");*/
var progress = new Progress<ICopyProgress>(
x =>
{
/*_wnd.PercentLabel.Dispatcher.Invoke(
() => _wnd.PercentLabel.Content = x.PercentComplete.ToString("P"),
DispatcherPriority.Background);
_wnd.ProgressBar.Dispatcher.Invoke(
() => _wnd.ProgressBar.Value = x.PercentComplete, DispatcherPriority.Background);*/
});
await using var fileStream = File.OpenWrite(_filename);
var task = client.GetAsync(url, fileStream, progress);
var response = await task;
if (task.IsCompletedSuccessfully)
{
/*_wnd.PercentLabel.Dispatcher.Invoke(
() => _wnd.PercentLabel.Content = "100,00%", DispatcherPriority.Background);
_wnd.ProgressBar.Dispatcher.Invoke(
() => _wnd.ProgressBar.Value = 1, DispatcherPriority.Background);*/
}
}
private static void Extract()
{
MyLogger.Log.Debug("Extract");
MyLogger.Log.Information("Start extraction...");
var options = new ReaderOptions {Password = ArchivePassword};
var archive = ArchiveFactory.Open(_filename, options);
var expression1 = new Regex(@"nonlog_build\\steam_api(?:64)?\.dll");
/*await _wnd.ProgressBar.Dispatcher.InvokeAsync(
() => _wnd.ProgressBar.IsIndeterminate = true, DispatcherPriority.ContextIdle);
await _wnd.FilenameLabel.Dispatcher.InvokeAsync(
() => _wnd.FilenameLabel.Content = _filename, DispatcherPriority.ContextIdle);
await _wnd.InfoLabel.Dispatcher.InvokeAsync(
() => _wnd.InfoLabel.Content = "Extracting...", DispatcherPriority.ContextIdle);
await _wnd.PercentLabel.Dispatcher.InvokeAsync(
() => _wnd.PercentLabel.Content = "100%", DispatcherPriority.ContextIdle);*/
foreach (var entry in archive.Entries)
{
// ReSharper disable once InvertIf
if (!entry.IsDirectory && expression1.IsMatch(entry.Key))
{
MyLogger.Log.Debug(entry.Key);
entry.WriteToDirectory(Directory.GetCurrentDirectory(), new ExtractionOptions
{
ExtractFullPath = false,
Overwrite = true
});
}
}
MyLogger.Log.Information("Extraction done!");
}
}
}