Browser app for consolidating all browser related tasks in a single place.

This commit is contained in:
Timothy Baldridge
2022-01-23 21:07:10 -07:00
parent b5a2354122
commit de64e5f35e
22 changed files with 1299 additions and 0 deletions

454
Wabbajack.Networking.Browser/.gitignore vendored Normal file
View File

@ -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

View File

@ -0,0 +1,12 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Wabbajack.Networking.Browser"
x:Class="Wabbajack.Networking.Browser.App">
<Application.DataTemplates>
<local:ViewLocator/>
</Application.DataTemplates>
<Application.Styles>
<FluentTheme Mode="Dark"/>
</Application.Styles>
</Application>

View File

@ -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<string>())
.ConfigureLogging(c => { c.ClearProviders(); })
.ConfigureServices((host, services) => { services.AddAppServices(); }).Build();
Services = host.Services;
// Need to startup the message bus;
var app = Services.GetService<CefAppImpl>();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
Program.MainWindow = Services.GetRequiredService<MainWindow>();
Program.MainWindowVM = Services.GetRequiredService<MainWindowViewModel>();
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);
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

View File

@ -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<Cookie[]> 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<HtmlDocument> GetDom(this WebView view, CancellationToken token)
{
var source = await view.GetMainFrame().GetSourceAsync(token);
var doc = new HtmlDocument();
doc.LoadHtml(source);
return doc;
}
}

View File

@ -0,0 +1,71 @@
using System;
using System.Runtime.InteropServices;
using CefNet;
namespace Wabbajack.Networking.Browser;
internal class CefAppImpl : CefNetApplication
{
public Action<long> 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);
}
}

View File

@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<ReactiveUI />
</Weavers>

View File

@ -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<App>()
.UsePlatformDetect()
.LogToTrace()
.UseReactiveUI();
}
}

View File

@ -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<MainWindow>();
services.AddSingleton<MainWindowViewModel>();
services.AddSingleton<IVerb, NexusLogin>();
services.AddSingleton<IVerb, LoverLabLogin>();
services.AddSingleton<IVerb, VectorPlexusLogin>();
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<CefSettings>());
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);
}
}

View File

@ -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<TLoginType> : AVerb
where TLoginType : OAuth2LoginState, new()
{
private readonly EncryptedJsonTokenProvider<TLoginType> _tokenProvider;
private readonly HttpClient _httpClient;
private readonly string _namePrefix;
private readonly ILogger _logger;
public AOAuthLoginVerb(ILogger logger, string namePrefix, EncryptedJsonTokenProvider<TLoginType> 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<string?, string?>[]
{
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<OAuthResultState>(cancellationToken: token);
await _tokenProvider.SetToken(new TLoginType
{
Cookies = cookies,
ResultState = data!
});
}
private class AsyncSchemeHandler : CefSchemeHandlerFactory
{
private readonly TaskCompletionSource<Uri> _tcs = new();
public Task<Uri> 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<Uri> _tcs;
public Handler(TaskCompletionSource<Uri> tcs)
{
_tcs = tcs;
}
protected override bool ProcessRequest(CefRequest request, CefCallback callback)
{
_tcs.TrySetResult(new Uri(request.Url));
return false;
}
}
}

View File

@ -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;
}

View File

@ -0,0 +1,8 @@
using System.CommandLine;
namespace Wabbajack.CLI.Verbs;
public interface IVerb
{
public Command MakeCommand();
}

View File

@ -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<LoversLabLoginState>
{
public LoverLabLogin(ILogger<LoverLabLogin> logger, EncryptedJsonTokenProvider<LoversLabLoginState> tokenProvider, HttpClient client) :
base(logger, "vector-plexus", tokenProvider, client)
{
}
}

View File

@ -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<NexusApiState> _tokenProvider;
public NexusLogin(ITokenProvider<NexusApiState> 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
});
}
}

View File

@ -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<VectorPlexusLoginState>
{
public VectorPlexusLogin(ILogger<LoverLabLogin> logger, EncryptedJsonTokenProvider<VectorPlexusLoginState> tokenProvider, HttpClient client) :
base(logger, "lovers-lab", tokenProvider, client)
{
}
}

View File

@ -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;
}
}
}

View File

@ -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<IVerb> _verbs;
public MainWindowViewModel(IEnumerable<IVerb> 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);
}
}
}

View File

@ -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; }
}
}

View File

@ -0,0 +1,30 @@
<reactiveUi:ReactiveWindow x:TypeArguments="vm:MainWindowViewModel"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:Wabbajack.Networking.Browser.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:avalonia="clr-namespace:CefNet.Avalonia;assembly=CefNet.Avalonia"
xmlns:reactiveUi="http://reactiveui.net"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="600"
x:Class="Wabbajack.Networking.Browser.Views.MainWindow"
Icon="/Assets/avalonia-logo.ico"
Title="Wabbajack.Networking.Browser"
Width="800"
Height="600"
TransparencyLevelHint="AcrylicBlur"
Background="Transparent"
ExtendClientAreaToDecorationsHint="True">
<Design.DataContext>
<vm:MainWindowViewModel/>
</Design.DataContext>
<Grid RowDefinitions="Auto, *"
ColumnDefinitions="Auto, *">
<TextBlock Grid.Row="0" Grid.Column="0" Margin="8" x:Name="Instructions" VerticalAlignment="Center" HorizontalAlignment="Left"></TextBlock>
<avalonia:WebView Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="2" x:FieldModifier="public" x:Name="Browser" Margin="4" InitialUrl="https://www.google.com"></avalonia:WebView>
</Grid>
</reactiveUi:ReactiveWindow>

View File

@ -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<MainWindowViewModel>
{
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);
});
}
}
}

View File

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<Folder Include="Models\" />
<AvaloniaResource Include="Assets\**" />
<None Remove=".gitignore" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.10.10" />
<PackageReference Include="Avalonia.Desktop" Version="0.10.10" />
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="0.10.10" />
<PackageReference Include="Avalonia.ReactiveUI" Version="0.10.10" />
<PackageReference Include="CefNet.Avalonia" Version="97.1.22018.1433" />
<PackageReference Include="Fizzler.Systems.HtmlAgilityPack" Version="1.2.1" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.40" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.2-mauipre.1.22054.8" />
<PackageReference Include="ReactiveUI.Fody" Version="17.1.17" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta1.21561.1" />
<PackageReference Include="XamlNameReferenceGenerator" Version="1.3.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Wabbajack.Common\Wabbajack.Common.csproj" />
<ProjectReference Include="..\Wabbajack.Paths.IO\Wabbajack.Paths.IO.csproj" />
<ProjectReference Include="..\Wabbajack.Services.OSIntegrated\Wabbajack.Services.OSIntegrated.csproj" />
</ItemGroup>
</Project>

View File

@ -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}