diff --git a/Wabbajack.Networking.Browser/.gitignore b/Wabbajack.Networking.Browser/.gitignore new file mode 100644 index 00000000..8afdcb63 --- /dev/null +++ b/Wabbajack.Networking.Browser/.gitignore @@ -0,0 +1,454 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# JetBrains Rider +.idea/ +*.sln.iml + +## +## Visual Studio Code +## +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json diff --git a/Wabbajack.Networking.Browser/App.axaml b/Wabbajack.Networking.Browser/App.axaml new file mode 100644 index 00000000..e6dea0e2 --- /dev/null +++ b/Wabbajack.Networking.Browser/App.axaml @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/Wabbajack.Networking.Browser/App.axaml.cs b/Wabbajack.Networking.Browser/App.axaml.cs new file mode 100644 index 00000000..fa599dc9 --- /dev/null +++ b/Wabbajack.Networking.Browser/App.axaml.cs @@ -0,0 +1,67 @@ +using System; +using System.Threading; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using Avalonia.Threading; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using ReactiveUI; +using Splat; +using Wabbajack.Networking.Browser.ViewModels; +using Wabbajack.Networking.Browser.Views; + +namespace Wabbajack.Networking.Browser +{ + public class App : Application + { + public static IServiceProvider Services { get; private set; } = null!; + public static Window? MainWindow { get; set; } + + public static event EventHandler FrameworkInitialized; + public static event EventHandler FrameworkShutdown; + + public override void Initialize() + { + Dispatcher.UIThread.Post(() => Thread.CurrentThread.Name = "UIThread"); + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + var host = Host.CreateDefaultBuilder(Array.Empty()) + .ConfigureLogging(c => { c.ClearProviders(); }) + .ConfigureServices((host, services) => { services.AddAppServices(); }).Build(); + Services = host.Services; + + + // Need to startup the message bus; + var app = Services.GetService(); + + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + Program.MainWindow = Services.GetRequiredService(); + Program.MainWindowVM = Services.GetRequiredService(); + Program.MainWindow.ViewModel = Program.MainWindowVM; + desktop.MainWindow = Program.MainWindow; + desktop.Startup += Startup; + desktop.Exit += Exit; + MainWindow = desktop.MainWindow; + } + + base.OnFrameworkInitializationCompleted(); + } + + private void Startup(object sender, ControlledApplicationLifetimeStartupEventArgs e) + { + FrameworkInitialized?.Invoke(this, EventArgs.Empty); + } + + private void Exit(object sender, ControlledApplicationLifetimeExitEventArgs e) + { + FrameworkShutdown?.Invoke(this, EventArgs.Empty); + } + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Assets/avalonia-logo.ico b/Wabbajack.Networking.Browser/Assets/avalonia-logo.ico new file mode 100644 index 00000000..da8d49ff Binary files /dev/null and b/Wabbajack.Networking.Browser/Assets/avalonia-logo.ico differ diff --git a/Wabbajack.Networking.Browser/BrowserExtensions.cs b/Wabbajack.Networking.Browser/BrowserExtensions.cs new file mode 100644 index 00000000..70064377 --- /dev/null +++ b/Wabbajack.Networking.Browser/BrowserExtensions.cs @@ -0,0 +1,67 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using CefNet; +using CefNet.Avalonia; +using HtmlAgilityPack; +using Wabbajack.DTOs.Logins; + +namespace Wabbajack.Networking.Browser; + +public static class BrowserExtensions +{ + public static async Task WaitForReady(this WebView browser) + { + while (!browser.IsInitialized) + { + await Task.Delay(250); + } + + while (browser.BrowserObject == null) + { + await Task.Delay(250); + } + } + + public static async Task NavigateTo(this WebView browser, Uri location) + { + browser.Navigate(location.ToString()); + await browser.WaitForIdle(); + } + + public static async Task WaitForIdle(this WebView browser) + { + while (browser.IsBusy) + { + await Task.Delay(250); + } + } + + public static async Task Cookies(this WebView view, string domainEnding, CancellationToken token) + { + var results = CefCookieManager.GetGlobalManager(null)!; + var cookies = await results.GetCookiesAsync(c => c.Domain.EndsWith(domainEnding), token)!; + return cookies.Select(c => new Cookie + { + Domain = c.Domain, + Name = c.Name, + Path = c.Path, + Value = c.Value + }).ToArray(); + } + + public static async Task EvaluateJavaScript(this WebView view, string js) + { + view.GetMainFrame().ExecuteJavaScript(js, "", 0); + } + + public static async Task GetDom(this WebView view, CancellationToken token) + { + var source = await view.GetMainFrame().GetSourceAsync(token); + var doc = new HtmlDocument(); + doc.LoadHtml(source); + return doc; + } + +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/CefAppImpl.cs b/Wabbajack.Networking.Browser/CefAppImpl.cs new file mode 100644 index 00000000..f1cbad00 --- /dev/null +++ b/Wabbajack.Networking.Browser/CefAppImpl.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.InteropServices; +using CefNet; + +namespace Wabbajack.Networking.Browser; + +internal class CefAppImpl : CefNetApplication +{ + public Action ScheduleMessagePumpWorkCallback { get; set; } + + protected override void OnBeforeCommandLineProcessing(string processType, CefCommandLine commandLine) + { + base.OnBeforeCommandLineProcessing(processType, commandLine); + + Console.WriteLine("ChromiumWebBrowser_OnBeforeCommandLineProcessing"); + Console.WriteLine(commandLine.CommandLineString); + + //commandLine.AppendSwitchWithValue("proxy-server", "127.0.0.1:8888"); + + + commandLine.AppendSwitchWithValue("remote-debugging-port", "9222"); + + //enable-devtools-experiments + commandLine.AppendSwitch("enable-devtools-experiments"); + + //e.CommandLine.AppendSwitchWithValue("user-agent", "Mozilla/5.0 (Windows 10.0) WebKa/" + DateTime.UtcNow.Ticks); + + //("force-device-scale-factor", "1"); + + //commandLine.AppendSwitch("disable-gpu"); + //commandLine.AppendSwitch("disable-gpu-compositing"); + //commandLine.AppendSwitch("disable-gpu-vsync"); + + commandLine.AppendSwitch("enable-begin-frame-scheduling"); + commandLine.AppendSwitch("enable-media-stream"); + + commandLine.AppendSwitchWithValue("enable-blink-features", "CSSPseudoHas"); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + commandLine.AppendSwitch("no-zygote"); + commandLine.AppendSwitch("no-sandbox"); + } + } + + protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) + { + base.OnContextCreated(browser, frame, context); + frame.ExecuteJavaScript(@" +{ +const newProto = navigator.__proto__; +delete newProto.webdriver; +navigator.__proto__ = newProto; +}", frame.Url, 0); + } + + protected override void OnCefProcessMessageReceived(CefProcessMessageReceivedEventArgs e) + { + base.OnCefProcessMessageReceived(e); + } + + protected override CefRenderProcessHandler GetRenderProcessHandler() + { + return base.GetRenderProcessHandler(); + } + + protected override void OnScheduleMessagePumpWork(long delayMs) + { + ScheduleMessagePumpWorkCallback(delayMs); + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/FodyWeavers.xml b/Wabbajack.Networking.Browser/FodyWeavers.xml new file mode 100644 index 00000000..63fc1484 --- /dev/null +++ b/Wabbajack.Networking.Browser/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Program.cs b/Wabbajack.Networking.Browser/Program.cs new file mode 100644 index 00000000..123e9b30 --- /dev/null +++ b/Wabbajack.Networking.Browser/Program.cs @@ -0,0 +1,37 @@ +using System; +using Avalonia; +using Avalonia.ReactiveUI; +using CefNet; +using Wabbajack.Networking.Browser.ViewModels; +using Wabbajack.Networking.Browser.Views; + +namespace Wabbajack.Networking.Browser +{ + class Program + { + public static MainWindowViewModel MainWindowVM { get; set; } + public static string[] Args { get; set; } + + public static Views.MainWindow MainWindow { get; set; } + + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + [STAThread] + public static void Main(string[] args) + { + Args = args; + BuildAvaloniaApp() + .StartWithCefNetApplicationLifetime(args); + + + } + + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .LogToTrace() + .UseReactiveUI(); + } +} diff --git a/Wabbajack.Networking.Browser/ServiceExtensions.cs b/Wabbajack.Networking.Browser/ServiceExtensions.cs new file mode 100644 index 00000000..a4209435 --- /dev/null +++ b/Wabbajack.Networking.Browser/ServiceExtensions.cs @@ -0,0 +1,83 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Threading; +using CefNet; +using Microsoft.Extensions.DependencyInjection; +using Wabbajack.CLI.Verbs; +using Wabbajack.Networking.Browser.Verbs; +using Wabbajack.Networking.Browser.ViewModels; +using Wabbajack.Networking.Browser.Views; +using Wabbajack.Paths.IO; +using Wabbajack.Services.OSIntegrated; + +namespace Wabbajack.Networking.Browser; + +public static class ServiceExtensions +{ + private const int messagePumpDelay = 10; + + + private static CefAppImpl app; + private static Timer messagePump; + + public static IServiceCollection AddAppServices(this IServiceCollection services) + { + + var resources = KnownFolders.EntryPoint; + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddOSIntegrated(); + + services.AddSingleton(s => new CefSettings + { + NoSandbox = true, + PersistSessionCookies = true, + MultiThreadedMessageLoop = false, + WindowlessRenderingEnabled = true, + ExternalMessagePump = true, + LocalesDirPath = resources.Combine("locales").ToString(), + ResourcesDirPath = resources.ToString(), + UserAgent = "", + CachePath = KnownFolders.WabbajackAppLocal.Combine("cef_cache").ToString() + }); + + services.AddSingleton(s => + { + App.FrameworkInitialized += App_FrameworkInitialized; + + var app = new CefAppImpl(); + app.ScheduleMessagePumpWorkCallback = OnScheduleMessagePumpWork; + + app.CefProcessMessageReceived += App_CefProcessMessageReceived; + app.Initialize(resources.ToString(), s.GetService()); + + + return app; + }); + + return services; + } + + private static async void OnScheduleMessagePumpWork(long delayMs) + { + await Task.Delay((int) delayMs); + Dispatcher.UIThread.Post(CefApi.DoMessageLoopWork); + } + + private static void App_CefProcessMessageReceived(object? sender, CefProcessMessageReceivedEventArgs e) + { + var msg = e.Name; + } + + private static void App_FrameworkInitialized(object? sender, EventArgs e) + { + if (CefNetApplication.Instance.UsesExternalMessageLoop) + messagePump = new Timer(_ => Dispatcher.UIThread.Post(CefApi.DoMessageLoopWork), null, messagePumpDelay, + messagePumpDelay); + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Verbs/AOAuthLoginVerb.cs b/Wabbajack.Networking.Browser/Verbs/AOAuthLoginVerb.cs new file mode 100644 index 00000000..29ff735b --- /dev/null +++ b/Wabbajack.Networking.Browser/Verbs/AOAuthLoginVerb.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.CommandLine; +using System.CommandLine.Invocation; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading; +using System.Threading.Tasks; +using System.Web; +using CefNet; +using Microsoft.Extensions.Logging; +using Wabbajack.CLI.Verbs; +using Wabbajack.DTOs.Logins; +using Wabbajack.Services.OSIntegrated; + +namespace Wabbajack.Networking.Browser.Verbs; + +public abstract class AOAuthLoginVerb : AVerb +where TLoginType : OAuth2LoginState, new() +{ + private readonly EncryptedJsonTokenProvider _tokenProvider; + private readonly HttpClient _httpClient; + private readonly string _namePrefix; + private readonly ILogger _logger; + + public AOAuthLoginVerb(ILogger logger, string namePrefix, EncryptedJsonTokenProvider tokenProvider, HttpClient client) + { + _logger = logger; + _tokenProvider = tokenProvider; + _httpClient = client; + _namePrefix = namePrefix; + + + } + + public override Command MakeCommand() + { + var command = new Command($"{_namePrefix}-login"); + command.Description = "Prompt the user to log into the nexus"; + command.Handler = CommandHandler.Create(Run); + return command; + } + + private async Task Run(CancellationToken token) + { + var tlogin = new TLoginType(); + + await Browser.WaitForReady(); + + var handler = new AsyncSchemeHandler(); + Browser.RequestContext.RegisterSchemeHandlerFactory("wabbajack", "", handler); + + Instructions = $"Please log in and allow Wabbajack to access your {tlogin.SiteName} account"; + + var scopes = string.Join(" ", tlogin.Scopes); + var state = Guid.NewGuid().ToString(); + + await Browser.NavigateTo(new Uri(tlogin.AuthorizationEndpoint + + $"?response_type=code&client_id={tlogin.ClientID}&state={state}&scope={scopes}")); + + var uri = await handler.Task.WaitAsync(token); + + var cookies = await Browser.Cookies(tlogin.AuthorizationEndpoint.Host, token); + + var parsed = HttpUtility.ParseQueryString(uri.Query); + if (parsed.Get("state") != state) + { + _logger.LogCritical("Bad OAuth state, this shouldn't happen"); + throw new Exception("Bad OAuth State"); + } + + if (parsed.Get("code") == null) + { + _logger.LogCritical("Bad code result from OAuth"); + throw new Exception("Bad code result from OAuth"); + } + + var authCode = parsed.Get("code"); + + var formData = new KeyValuePair[] + { + new("grant_type", "authorization_code"), + new("code", authCode), + new("client_id", tlogin.ClientID) + }; + + var msg = new HttpRequestMessage(); + msg.Method = HttpMethod.Post; + msg.RequestUri = tlogin.TokenEndpoint; + msg.Headers.Add("User-Agent", + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"); + msg.Headers.Add("Cookie", string.Join(";", cookies.Select(c => $"{c.Name}={c.Value}"))); + msg.Content = new FormUrlEncodedContent(formData.ToList()); + + using var response = await _httpClient.SendAsync(msg, token); + var data = await response.Content.ReadFromJsonAsync(cancellationToken: token); + + await _tokenProvider.SetToken(new TLoginType + { + Cookies = cookies, + ResultState = data! + }); + } + + private class AsyncSchemeHandler : CefSchemeHandlerFactory + { + private readonly TaskCompletionSource _tcs = new(); + + public Task Task => _tcs.Task; + + protected override CefResourceHandler Create(CefBrowser browser, CefFrame frame, string schemeName, + CefRequest request) + { + return new Handler(_tcs); + } + } + + private class Handler : CefResourceHandler + { + private readonly TaskCompletionSource _tcs; + + public Handler(TaskCompletionSource tcs) + { + _tcs = tcs; + } + + protected override bool ProcessRequest(CefRequest request, CefCallback callback) + { + _tcs.TrySetResult(new Uri(request.Url)); + return false; + } + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Verbs/AVerb.cs b/Wabbajack.Networking.Browser/Verbs/AVerb.cs new file mode 100644 index 00000000..bead91f4 --- /dev/null +++ b/Wabbajack.Networking.Browser/Verbs/AVerb.cs @@ -0,0 +1,26 @@ +using System.CommandLine; +using Avalonia.Threading; +using CefNet.Avalonia; +using ReactiveUI; +using Wabbajack.Networking.Browser; + +namespace Wabbajack.CLI.Verbs; + +public abstract class AVerb : IVerb +{ + public abstract Command MakeCommand(); + + public string Instructions + { + set + { + Dispatcher.UIThread.Post(() => + { + + Program.MainWindowVM.Instructions = value; + }); + } + } + + public WebView Browser => Program.MainWindow.Browser; +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Verbs/IVerb.cs b/Wabbajack.Networking.Browser/Verbs/IVerb.cs new file mode 100644 index 00000000..433c350c --- /dev/null +++ b/Wabbajack.Networking.Browser/Verbs/IVerb.cs @@ -0,0 +1,8 @@ +using System.CommandLine; + +namespace Wabbajack.CLI.Verbs; + +public interface IVerb +{ + public Command MakeCommand(); +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Verbs/LoverLabLogin.cs b/Wabbajack.Networking.Browser/Verbs/LoverLabLogin.cs new file mode 100644 index 00000000..0fb599ee --- /dev/null +++ b/Wabbajack.Networking.Browser/Verbs/LoverLabLogin.cs @@ -0,0 +1,15 @@ +using System.Net.Http; +using JetBrains.Annotations; +using Microsoft.Extensions.Logging; +using Wabbajack.DTOs.Logins; +using Wabbajack.Services.OSIntegrated; + +namespace Wabbajack.Networking.Browser.Verbs; + +public class LoverLabLogin : AOAuthLoginVerb +{ + public LoverLabLogin(ILogger logger, EncryptedJsonTokenProvider tokenProvider, HttpClient client) : + base(logger, "vector-plexus", tokenProvider, client) + { + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Verbs/NexusLogin.cs b/Wabbajack.Networking.Browser/Verbs/NexusLogin.cs new file mode 100644 index 00000000..a67c84cb --- /dev/null +++ b/Wabbajack.Networking.Browser/Verbs/NexusLogin.cs @@ -0,0 +1,108 @@ +using System; +using System.CommandLine; +using System.CommandLine.Invocation; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Fizzler.Systems.HtmlAgilityPack; +using ReactiveUI; +using Wabbajack.CLI.Verbs; +using Wabbajack.DTOs.Logins; +using Wabbajack.Networking.Http.Interfaces; + +namespace Wabbajack.Networking.Browser.Verbs; + +public class NexusLogin : AVerb +{ + private readonly ITokenProvider _tokenProvider; + + public NexusLogin(ITokenProvider tokenProvider) + { + _tokenProvider = tokenProvider; + } + public override Command MakeCommand() + { + var command = new Command("nexus-login"); + command.Description = "Prompt the user to log into the nexus"; + command.Handler = CommandHandler.Create(Run); + return command; + } + + private async Task Run(CancellationToken token) + { + token.ThrowIfCancellationRequested(); + + Instructions = "Please log into the Nexus"; + + await Browser.WaitForReady(); + + await Browser.NavigateTo(new Uri( + "https://users.nexusmods.com/auth/continue?client_id=nexus&redirect_uri=https://www.nexusmods.com/oauth/callback&response_type=code&referrer=//www.nexusmods.com")); + + Cookie[] cookies = { }; + while (true) + { + cookies = await Browser.Cookies("nexusmods.com", token); + if (cookies.Any(c => c.Name == "member_id")) + break; + + token.ThrowIfCancellationRequested(); + await Task.Delay(500, token); + } + + Instructions = "Getting API Key..."; + + await Browser.NavigateTo(new Uri("https://www.nexusmods.com/users/myaccount?tab=api")); + + + await Browser.NavigateTo(new Uri("https://www.nexusmods.com/users/myaccount?tab=api")); + + var key = ""; + + while (true) + { + try + { + key = (await Browser.GetDom(token)) + .DocumentNode + .QuerySelectorAll("input[value=wabbajack]") + .SelectMany(p => p.ParentNode.ParentNode.QuerySelectorAll("textarea.application-key")) + .Select(node => node.InnerHtml) + .FirstOrDefault() ?? ""; + } + catch (Exception) + { + // ignored + } + + if (!string.IsNullOrEmpty(key)) + break; + + try + { + await Browser.EvaluateJavaScript( + "var found = document.querySelector(\"input[value=wabbajack]\").parentElement.parentElement.querySelector(\"form button[type=submit]\");" + + "found.onclick= function() {return true;};" + + "found.class = \" \"; " + + "found.click();" + + "found.remove(); found = undefined;" + ); + Instructions = "Generating API Key, Please Wait..."; + } + catch (Exception) + { + // ignored + } + + token.ThrowIfCancellationRequested(); + } + + Instructions = "Success, saving information..."; + await _tokenProvider.SetToken(new NexusApiState + { + Cookies = cookies, + ApiKey = key + }); + + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Verbs/VectorPlexusLogin.cs b/Wabbajack.Networking.Browser/Verbs/VectorPlexusLogin.cs new file mode 100644 index 00000000..1caf245a --- /dev/null +++ b/Wabbajack.Networking.Browser/Verbs/VectorPlexusLogin.cs @@ -0,0 +1,14 @@ +using System.Net.Http; +using Microsoft.Extensions.Logging; +using Wabbajack.DTOs.Logins; +using Wabbajack.Services.OSIntegrated; + +namespace Wabbajack.Networking.Browser.Verbs; + +public class VectorPlexusLogin : AOAuthLoginVerb +{ + public VectorPlexusLogin(ILogger logger, EncryptedJsonTokenProvider tokenProvider, HttpClient client) : + base(logger, "lovers-lab", tokenProvider, client) + { + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/ViewLocator.cs b/Wabbajack.Networking.Browser/ViewLocator.cs new file mode 100644 index 00000000..c11ec087 --- /dev/null +++ b/Wabbajack.Networking.Browser/ViewLocator.cs @@ -0,0 +1,30 @@ +using System; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using Wabbajack.Networking.Browser.ViewModels; + +namespace Wabbajack.Networking.Browser +{ + public class ViewLocator : IDataTemplate + { + public IControl Build(object data) + { + var name = data.GetType().FullName!.Replace("ViewModel", "View"); + var type = Type.GetType(name); + + if (type != null) + { + return (Control)Activator.CreateInstance(type)!; + } + else + { + return new TextBlock { Text = "Not Found: " + name }; + } + } + + public bool Match(object data) + { + return data is ViewModelBase; + } + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/ViewModels/MainWindowViewModel.cs b/Wabbajack.Networking.Browser/ViewModels/MainWindowViewModel.cs new file mode 100644 index 00000000..26375cb5 --- /dev/null +++ b/Wabbajack.Networking.Browser/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.CommandLine; +using System.Reactive.Disposables; +using System.Text; +using System.Threading.Tasks; +using ReactiveUI; +using ReactiveUI.Fody.Helpers; +using Wabbajack.CLI.Verbs; +using Wabbajack.Common; + +namespace Wabbajack.Networking.Browser.ViewModels +{ + public class MainWindowViewModel : ViewModelBase + { + private readonly IEnumerable _verbs; + + public MainWindowViewModel(IEnumerable verbs) + { + _verbs = verbs; + this.WhenActivated(disposables => + { + ExecuteCommand().FireAndForget(); + Disposable.Empty.DisposeWith(disposables); + }); + } + + [Reactive] + public string Instructions { get; set; } + + private async Task ExecuteCommand() + { + while (Program.MainWindow.Browser == null) + await Task.Delay(250); + + var root = new RootCommand(); + foreach (var verb in _verbs) + root.Add(verb.MakeCommand()); + + var code = await root.InvokeAsync(Program.Args); + Environment.Exit(code); + } + } +} diff --git a/Wabbajack.Networking.Browser/ViewModels/ViewModelBase.cs b/Wabbajack.Networking.Browser/ViewModels/ViewModelBase.cs new file mode 100644 index 00000000..07911712 --- /dev/null +++ b/Wabbajack.Networking.Browser/ViewModels/ViewModelBase.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; +using ReactiveUI; + +namespace Wabbajack.Networking.Browser.ViewModels +{ + public class ViewModelBase : ReactiveObject, IActivatableViewModel + { + public ViewModelBase() + { + Activator = new ViewModelActivator(); + } + + public ViewModelActivator Activator { get; } + } +} diff --git a/Wabbajack.Networking.Browser/Views/MainWindow.axaml b/Wabbajack.Networking.Browser/Views/MainWindow.axaml new file mode 100644 index 00000000..33a78bb5 --- /dev/null +++ b/Wabbajack.Networking.Browser/Views/MainWindow.axaml @@ -0,0 +1,30 @@ + + + + + + + + + + + diff --git a/Wabbajack.Networking.Browser/Views/MainWindow.axaml.cs b/Wabbajack.Networking.Browser/Views/MainWindow.axaml.cs new file mode 100644 index 00000000..00ef6e30 --- /dev/null +++ b/Wabbajack.Networking.Browser/Views/MainWindow.axaml.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using System.CommandLine; +using System.Reactive.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Mixins; +using Avalonia.Markup.Xaml; +using Avalonia.ReactiveUI; +using Avalonia.Threading; +using CefNet.Avalonia; +using ReactiveUI; +using Wabbajack.CLI.Verbs; +using Wabbajack.Common; +using Wabbajack.Networking.Browser.ViewModels; + +namespace Wabbajack.Networking.Browser.Views +{ + public partial class MainWindow + : ReactiveWindow + { + + public MainWindow() + { + InitializeComponent(); +#if DEBUG + this.AttachDevTools(); +#endif + this.WhenActivated(disposables => + { + ViewModel.WhenAnyValue(vm => vm.Instructions) + .ObserveOn(RxApp.MainThreadScheduler) + .Select(v => v) + .BindTo(this, view => view.Instructions.Text) + .DisposeWith(disposables); + + }); + } + + } +} \ No newline at end of file diff --git a/Wabbajack.Networking.Browser/Wabbajack.Networking.Browser.csproj b/Wabbajack.Networking.Browser/Wabbajack.Networking.Browser.csproj new file mode 100644 index 00000000..9aefeb0e --- /dev/null +++ b/Wabbajack.Networking.Browser/Wabbajack.Networking.Browser.csproj @@ -0,0 +1,32 @@ + + + WinExe + net6.0 + enable + latest + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Wabbajack.sln b/Wabbajack.sln index f0008b0d..dc336c52 100644 --- a/Wabbajack.sln +++ b/Wabbajack.sln @@ -125,6 +125,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Wabbajack.App.Blazor", "Wab EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{18E36813-CB53-4172-8FF3-EFE3B9B30A5F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wabbajack.Networking.Browser", "Wabbajack.Networking.Browser\Wabbajack.Networking.Browser.csproj", "{44860A8E-C3E4-4BF0-8EAB-BFA2D6DA217A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -339,6 +341,10 @@ Global {C6E9B15D-510F-4074-AB1C-069F36BA4622}.Debug|Any CPU.Build.0 = Debug|Any CPU {C6E9B15D-510F-4074-AB1C-069F36BA4622}.Release|Any CPU.ActiveCfg = Release|Any CPU {C6E9B15D-510F-4074-AB1C-069F36BA4622}.Release|Any CPU.Build.0 = Release|Any CPU + {44860A8E-C3E4-4BF0-8EAB-BFA2D6DA217A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {44860A8E-C3E4-4BF0-8EAB-BFA2D6DA217A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {44860A8E-C3E4-4BF0-8EAB-BFA2D6DA217A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {44860A8E-C3E4-4BF0-8EAB-BFA2D6DA217A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -380,6 +386,7 @@ Global {4F252332-CA77-41DE-95A8-9DF38A81D675} = {98B731EE-4FC0-4482-A069-BCBA25497871} {AB9A5C22-10CC-4EE0-A808-FB1DC9E24247} = {F01F8595-5FD7-4506-8469-F4A5522DACC1} {D6351587-CAF6-4CB6-A2BD-5368E69F297C} = {F01F8595-5FD7-4506-8469-F4A5522DACC1} + {44860A8E-C3E4-4BF0-8EAB-BFA2D6DA217A} = {F01F8595-5FD7-4506-8469-F4A5522DACC1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {0AA30275-0F38-4A7D-B645-F5505178DDE8}