Init commit

This commit is contained in:
Jeddunk 2020-12-20 01:14:40 +01:00
commit 9e4f67f86a
26 changed files with 1785 additions and 0 deletions

216
Model/CacheModel.cs Normal file
View file

@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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.POCOs;
using auto_creamapi.Utils;
using NinjaNye.SearchExtensions;
using NinjaNye.SearchExtensions.Models;
using SteamStorefrontAPI;
namespace auto_creamapi.Model
{
public class CacheModel
{
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 static List<POCOs.App> _cache = new List<POCOs.App>();
public 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<CacheModel> Lazy =
new Lazy<CacheModel>(() => new CacheModel());
public static CacheModel Instance => Lazy.Value;
private CacheModel()
{
UpdateCache();
}
private static void UpdateCache()
{
var updateNeeded = DateTime.Now.Subtract(File.GetCreationTimeUtc(CachePath)).TotalDays >= 1;
string cacheString;
if (updateNeeded)
{
MyLogger.Log.Information("Updating cache...");
var client = new HttpClient();
var httpCall = client.GetAsync(SteamUri);
var response = httpCall.Result;
var readAsStringAsync = response.Content.ReadAsStringAsync();
var responseBody = readAsStringAsync.Result;
/*var writeAllTextAsync = File.WriteAllTextAsync(CachePath, responseBody, Encoding.UTF8);
writeAllTextAsync.RunSynchronously();*/
File.WriteAllText(CachePath, responseBody, Encoding.UTF8);
cacheString = responseBody;
}
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 EnumerableStringSearch<POCOs.App> GetListOfAppsByName(string name)
{
var listOfAppsByName = _cache.Search(x => x.Name)
.SetCulture(StringComparison.OrdinalIgnoreCase)
.ContainingAll(name.Split(' '));
return listOfAppsByName;
}
public POCOs.App 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 POCOs.App 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<POCOs.App>> GetListOfDlc(POCOs.App app, bool useSteamDb)
{
MyLogger.Log.Information("Get DLC");
var dlcList = new List<POCOs.App>();
if (app != null)
{
var task = AppDetails.GetAsync(app.AppId);
var steamApp = await task;
steamApp?.DLC.ForEach(x =>
{
var result = _cache.Find(y => y.AppId.Equals(x)) ??
new POCOs.App {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/{app.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 POCOs.App {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 find game: {app}");
}
return dlcList;
}
}
}

184
Model/CreamConfigModel.cs Normal file
View file

@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using auto_creamapi.Utils;
using IniParser;
using IniParser.Model;
namespace auto_creamapi.Model
{
public sealed class CreamConfigModel
{
// ReSharper disable once MemberCanBePrivate.Global
public struct CreamConfig
{
public int AppId;
public string Language;
public bool UnlockAll;
public bool ExtraProtection;
public bool ForceOffline;
public Dictionary<int, string> DlcList;
}
private CreamConfig _config;
public CreamConfig Config => _config;
private static readonly Lazy<CreamConfigModel> Lazy =
new Lazy<CreamConfigModel>(() => new CreamConfigModel());
public static CreamConfigModel Instance => Lazy.Value;
// ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once UnusedAutoPropertyAccessor.Global
private string _configFilePath;
private CreamConfigModel()
{
_config.DlcList = new Dictionary<int, string>();
SetConfigData();
}
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);
SetConfigData(); // 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);
}
}
else
{
MyLogger.Log.Information($"Config file does not exist @ {configFilePath}, skipping...");
SetConfigData();
}
}
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");
foreach (var (key, value) in _config.DlcList)
{
data["dlc"].AddKey(key.ToString(), value);
}
parser.WriteFile(_configFilePath, data, Encoding.UTF8);
}
public void SetConfigData()
{
_config.AppId = 0;
_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);
}
/*private void SetConfigData(int appId,
string language,
bool unlockAll,
bool extraProtection,
bool forceOffline,
List<POCOs.App> dlcList)
{
_config.AppId = appId;
_config.Language = language;
_config.UnlockAll = unlockAll;
_config.ExtraProtection = extraProtection;
_config.ForceOffline = forceOffline;
SetDlcFromAppList(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(int.Parse(match.Groups["id"].Value), match.Groups["name"].Value);
}
}
}
/*private void SetDlcFromAppList(List<POCOs.App> 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)
{
foreach (var (key, value) in _config.DlcList)
{
str += $" {key}={value},\n";
}
}
str += "]";
return str;
}
public bool ConfigExists()
{
return File.Exists(_configFilePath);
}
}
}

244
Model/CreamDllModel.cs Normal file
View file

@ -0,0 +1,244 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Threading;
using auto_creamapi.Utils;
using SharpCompress.Archives;
using SharpCompress.Common;
using SharpCompress.Readers;
using HttpProgress;
namespace auto_creamapi.Model
{
public class CreamDllModel
{
private struct CreamDll
{
public readonly string Filename;
public readonly string OrigFilename;
public readonly string Hash;
public CreamDll(string filename, string origFilename)
{
Filename = filename;
OrigFilename = origFilename;
Hash = "";
using var md5 = MD5.Create();
using var stream = File.OpenRead(Filename);
Hash = BitConverter
.ToString(md5.ComputeHash(stream))
.Replace("-", string.Empty);
}
}
private static readonly Lazy<CreamDllModel> Lazy =
new Lazy<CreamDllModel>(() => new CreamDllModel());
public static CreamDllModel Instance => Lazy.Value;
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;
private CreamDllModel()
{
if (!(File.Exists("steam_api.dll") && File.Exists("steam_api64.dll")))
{
MyLogger.Log.Information("Missing files, trying to download...");
new Action(async() => await DownloadDll(CsRinRuLogin.Username, CsRinRuLogin.Password))();
}
else
{
Init();
}
}
private void Init()
{
_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}"
});
}
}
private async Task DownloadDll(string username, string password)
{
var wnd = new DownloadWindow();
wnd.Show();
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")
});
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();
MyLogger.Log.Information("Start download...");
wnd.FilenameLabel.Content = filename;
/*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.Content = x.PercentComplete.ToString("P");
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.Content = "100,00%";
wnd.ProgressBar.Value = 1;
}*/
}
MyLogger.Log.Information("Start extraction...");
var options = new ReaderOptions {Password = "cs.rin.ru"};
var archive = ArchiveFactory.Open(filename, options);
var expression1 = new Regex(@"nonlog_build\\steam_api(?:64)?\.dll");
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!");
wnd.Close();
Init();
}
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($"Creating CreamAPI DLL @ {targetSteamApiDll}");
// 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 CheckExistence()
{
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 "";
}
}
}
}