Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix manual downloads sometimes launching in browser and related issues #2380

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions Wabbajack.App.Wpf/LauncherUpdater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.CompilerServices;
using Newtonsoft.Json;
using Wabbajack.Common;
using Wabbajack.Downloaders;
using Wabbajack.DTOs;
using Wabbajack.DTOs.DownloadStates;
Expand All @@ -27,9 +28,9 @@ public class LauncherUpdater
private readonly HttpClient _client;
private readonly Client _wjclient;
private readonly DTOSerializer _dtos;

private readonly DownloadDispatcher _downloader;

private static Uri GITHUB_REPO_RELEASES = new("https://api.github.com/repos/wabbajack-tools/wabbajack/releases");

public LauncherUpdater(ILogger<LauncherUpdater> logger, HttpClient client, Client wjclient, DTOSerializer dtos,
Expand All @@ -41,8 +42,8 @@ public LauncherUpdater(ILogger<LauncherUpdater> logger, HttpClient client, Clien
_dtos = dtos;
_downloader = downloader;
}


public static Lazy<AbsolutePath> CommonFolder = new (() =>
{
var entryPoint = KnownFolders.EntryPoint;
Expand Down Expand Up @@ -105,7 +106,7 @@ public async Task Run()

var launcherFolder = KnownFolders.EntryPoint.Parent;
var exePath = launcherFolder.Combine("Wabbajack.exe");

var launcherVersion = FileVersionInfo.GetVersionInfo(exePath.ToString());

if (release != default && release.version > Version.Parse(launcherVersion.FileVersion!))
Expand All @@ -119,7 +120,7 @@ await _downloader.Download(new Archive
Name = release.asset.Name,
Size = release.asset.Size
}, tempPath, CancellationToken.None);

if (tempPath.Size() != release.asset.Size)
{
_logger.LogInformation(
Expand All @@ -130,12 +131,12 @@ await _downloader.Download(new Archive
if (exePath.FileExists())
exePath.Delete();
await tempPath.MoveToAsync(exePath, true, CancellationToken.None);

_logger.LogInformation("Finished updating wabbajack");
await _wjclient.SendMetric("updated_launcher", $"{launcherVersion.FileVersion} -> {release.version}");
}
}

private async Task<Release[]> GetReleases()
{
_logger.LogInformation("Getting new Wabbajack version list");
Expand All @@ -146,7 +147,7 @@ private async Task<Release[]> GetReleases()
private HttpRequestMessage MakeMessage(Uri uri)
{
var msg = new HttpRequestMessage(HttpMethod.Get, uri);
msg.UseChromeUserAgent();
msg.AddChromeAgent();
return msg;
}

Expand Down
15 changes: 6 additions & 9 deletions Wabbajack.App.Wpf/UserIntervention/ManualDownloadHandler.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using System.Security.Policy;
using System.Threading;
using System.Threading.Tasks;
using Wabbajack.DTOs;
using Wabbajack.DTOs.DownloadStates;
using Wabbajack.DTOs.Interventions;
using Wabbajack.Paths;

namespace Wabbajack.UserIntervention;

Expand All @@ -17,18 +14,18 @@ protected override async Task Run(CancellationToken token)
//await WaitForReady();
var archive = Intervention.Archive;
var md = Intervention.Archive.State as Manual;

HeaderText = $"Manual download ({md.Url.Host})";

Instructions = string.IsNullOrWhiteSpace(md.Prompt) ? $"Please download {archive.Name}" : md.Prompt;
await NavigateTo(md.Url);

Instructions = string.IsNullOrWhiteSpace(md.Prompt) ? $"Please download {archive.Name}" : md.Prompt;

var uri = await WaitForDownloadUri(token, async () =>
var task = WaitForDownloadUri(token, async () =>
{
await RunJavaScript("Array.from(document.getElementsByTagName(\"iframe\")).forEach(f => f.remove())");
});

await NavigateTo(md.Url);
var uri = await task;

Intervention.Finish(uri);
}
}
10 changes: 5 additions & 5 deletions Wabbajack.App.Wpf/UserIntervention/OAuth2LoginHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Web;
using Microsoft.Extensions.Logging;
using ReactiveUI;
using Wabbajack.Common;
using Wabbajack.DTOs.Interventions;
using Wabbajack.DTOs.Logins;
using Wabbajack.Messages;
Expand Down Expand Up @@ -40,7 +41,7 @@ protected override async Task Run(CancellationToken token)

var tcs = new TaskCompletionSource<Uri>();
await NavigateTo(tlogin.AuthorizationEndpoint);

Browser!.Browser.CoreWebView2.Settings.UserAgent = "Wabbajack";
Browser!.Browser.NavigationStarting += (sender, args) =>
{
Expand All @@ -50,7 +51,7 @@ protected override async Task Run(CancellationToken token)
tcs.TrySetResult(uri);
}
};

Instructions = $"Please log in and allow Wabbajack to access your {tlogin.SiteName} account";

var scopes = string.Join(" ", tlogin.Scopes);
Expand Down Expand Up @@ -88,8 +89,7 @@ await NavigateTo(new Uri(tlogin.AuthorizationEndpoint +
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.AddChromeAgent();
msg.Headers.Add("Cookie", string.Join(";", cookies.Select(c => $"{c.Name}={c.Value}")));
msg.Content = new FormUrlEncodedContent(formData.ToList());

Expand All @@ -101,6 +101,6 @@ await _tokenProvider.SetToken(new TLoginType
Cookies = cookies,
ResultState = data!
});

}
}
27 changes: 19 additions & 8 deletions Wabbajack.App.Wpf/View Models/BrowserWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public abstract class BrowserWindowViewModel : ViewModel
[Reactive] public string HeaderText { get; set; }

[Reactive] public string Instructions { get; set; }

[Reactive] public string Address { get; set; }

public BrowserWindow? Browser { get; set; }
Expand Down Expand Up @@ -83,6 +83,11 @@ public async Task RunJavaScript(string script)

public async Task<Cookie[]> GetCookies(string domainEnding, CancellationToken token)
{
// Strip www. before searching for cookies on a domain to handle websites saving their cookies like .example.org
if (domainEnding.StartsWith("www."))
{
domainEnding = domainEnding[4..];
}
var cookies = (await _browser.CoreWebView2.CookieManager.GetCookiesAsync(""))
.Where(c => c.Domain.EndsWith(domainEnding));
return cookies.Select(c => new Cookie
Expand Down Expand Up @@ -112,18 +117,20 @@ public async Task<HtmlDocument> GetDom(CancellationToken token)
{
var source = new TaskCompletionSource<Uri>();
var referer = _browser.Source;
while (_browser.CoreWebView2 == null)
await Task.Delay(10, token);

_browser.CoreWebView2.DownloadStarting += (sender, args) =>
{
try
{

source.SetResult(new Uri(args.DownloadOperation.Uri));
}
catch (Exception)
{
source.SetCanceled();
}

args.Cancel = true;
args.Handled = true;
};
Expand All @@ -144,12 +151,16 @@ public async Task<HtmlDocument> GetDom(CancellationToken token)
}

var cookies = await GetCookies(uri.Host, token);
return new ManualDownload.BrowserDownloadState(uri, cookies, new[]
{
("Referer", referer.ToString())
});
return new ManualDownload.BrowserDownloadState(
uri,
cookies,
new[]
{
("Referer", referer?.ToString() ?? uri.ToString())
},
_browser.CoreWebView2.Settings.UserAgent);
}

public async Task<Hash> WaitForDownload(AbsolutePath path, CancellationToken token)
{
var source = new TaskCompletionSource();
Expand Down
20 changes: 11 additions & 9 deletions Wabbajack.Common/HttpExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,21 @@ namespace Wabbajack.Common;

public static class HttpExtensions
{
private const string ChromeUserAgent =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36";
public static HttpRequestMessage AddCookies(this HttpRequestMessage msg, Cookie[] cookies)
{
msg.Headers.Add("Cookie", string.Join(";", cookies.Select(c => $"{c.Name}={c.Value}")));
return msg;
}


public static HttpRequestMessage AddChromeAgent(this HttpRequestMessage msg, string? overrideUserAgent = null)
{
msg.Headers.UserAgent.Clear();
msg.Headers.Add("User-Agent", overrideUserAgent ?? ChromeUserAgent);
return msg;
}

public static HttpRequestMessage AddHeaders(this HttpRequestMessage msg, IEnumerable<(string Key, string Value)> headers)
{
foreach (var header in headers)
Expand All @@ -29,17 +38,10 @@ public static HttpRequestMessage AddHeaders(this HttpRequestMessage msg, IEnumer
return msg;
}

public static HttpRequestMessage AddChromeAgent(this HttpRequestMessage msg)
{
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");
return msg;
}

public static HttpRequestMessage ToHttpRequestMessage(this ManualDownload.BrowserDownloadState browserState)
{
var msg = new HttpRequestMessage(HttpMethod.Get, browserState.Uri);
msg.AddChromeAgent();
msg.AddChromeAgent(browserState.UserAgent);
msg.AddCookies(browserState.Cookies);
msg.AddHeaders(browserState.Headers);
return msg;
Expand Down
6 changes: 3 additions & 3 deletions Wabbajack.DTOs/Interventions/ManualDownload.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ namespace Wabbajack.DTOs.Interventions;
public class ManualDownload : AUserIntervention<ManualDownload.BrowserDownloadState>
{
public Archive Archive { get; }

public ManualDownload(Archive archive)
{
Archive = archive;
}

public record BrowserDownloadState(Uri Uri, Cookie[] Cookies, (string Key, string Value)[] Headers)
public record BrowserDownloadState(Uri Uri, Cookie[] Cookies, (string Key, string Value)[] Headers, string UserAgent)
{

}
}
22 changes: 11 additions & 11 deletions Wabbajack.Downloaders.GoogleDrive/GoogleDriveDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public Uri UnParse(IDownloadState state)
return new Uri(
$"https://drive.google.com/uc?id={(state as DTOs.DownloadStates.GoogleDrive)?.Id}&export=download");
}

public override IDownloadState? Resolve(IReadOnlyDictionary<string, string> iniData)
{
if (iniData.ContainsKey("directURL") && Uri.TryCreate(iniData["directURL"].CleanIniString(), UriKind.Absolute, out var uri))
Expand All @@ -74,8 +74,8 @@ public Uri UnParse(IDownloadState state)
}

public override Priority Priority => Priority.Normal;


public async Task<T> DownloadStream<T>(Archive archive, Func<Stream, Task<T>> fn, CancellationToken token)
{
var state = archive.State as DTOs.DownloadStates.GoogleDrive;
Expand Down Expand Up @@ -112,8 +112,8 @@ public override IEnumerable<string> MetaIni(Archive a, DTOs.DownloadStates.Googl
{
var initialUrl = $"https://drive.google.com/uc?id={state.Id}&export=download";
var msg = new HttpRequestMessage(HttpMethod.Get, initialUrl);
msg.UseChromeUserAgent();
msg.AddChromeAgent();

using var response = await _client.SendAsync(msg, token);
var cookies = response.GetSetCookies();
var warning = cookies.FirstOrDefault(c => c.Key.StartsWith("download_warning_"));
Expand All @@ -124,7 +124,7 @@ public override IEnumerable<string> MetaIni(Archive a, DTOs.DownloadStates.Googl
var txt = await response.Content.ReadAsStringAsync(token);
if (txt.Contains("<title>Google Drive - Quota exceeded</title>"))
throw new Exception("Google Drive - Quota Exceeded");

doc.LoadHtml(txt);

var action = doc.DocumentNode.DescendantsAndSelf()
Expand All @@ -133,7 +133,7 @@ public override IEnumerable<string> MetaIni(Archive a, DTOs.DownloadStates.Googl
.Select(d => d.GetAttributeValue("action", ""))
.FirstOrDefault();

if (action != null)
if (action != null)
warning = ("download_warning_", "t");

}
Expand All @@ -145,18 +145,18 @@ public override IEnumerable<string> MetaIni(Archive a, DTOs.DownloadStates.Googl

var url = $"https://drive.google.com/uc?export=download&confirm={warning.Value}&id={state.Id}";
var httpState = new HttpRequestMessage(HttpMethod.Get, url);
httpState.UseChromeUserAgent();
httpState.AddChromeAgent();
return httpState;
}
else
{
var url = $"https://drive.google.com/file/d/{state.Id}/edit";
var msg = new HttpRequestMessage(HttpMethod.Get, url);
msg.UseChromeUserAgent();
msg.AddChromeAgent();

using var response = await _client.SendAsync(msg, token);
msg = new HttpRequestMessage(HttpMethod.Get, url);
msg.UseChromeUserAgent();
msg.AddChromeAgent();
return !response.IsSuccessStatusCode ? null : msg;
}
}
Expand Down
7 changes: 0 additions & 7 deletions Wabbajack.Networking.Http/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,6 @@ namespace Wabbajack.Networking.Http;

public static class Extensions
{
public static HttpRequestMessage UseChromeUserAgent(this HttpRequestMessage msg)
{
msg.Headers.UserAgent.Clear();
msg.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");
return msg;
}

public static async Task<T> GetJsonFromSendAsync<T>(this HttpClient client, HttpRequestMessage msg,
JsonSerializerOptions opts, CancellationToken? token = null)
{
Expand Down
Loading