wabbajack/Wabbajack.Lib/Downloaders/GoogleDriveDownloader.cs

97 lines
3.3 KiB
C#
Raw Normal View History

using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Wabbajack.Common;
using Wabbajack.Common.Exceptions;
using Wabbajack.Common.Serialization.Json;
using Wabbajack.Lib.Validation;
namespace Wabbajack.Lib.Downloaders
{
public class GoogleDriveDownloader : IDownloader, IUrlDownloader
{
public async Task<AbstractDownloadState?> GetDownloaderState(dynamic archiveINI, bool quickMode)
{
2019-11-21 15:51:57 +00:00
var url = archiveINI?.General?.directURL;
return GetDownloaderState(url);
}
public AbstractDownloadState? GetDownloaderState(string url)
{
if (url != null && url.StartsWith("https://drive.google.com"))
{
var regex = new Regex("((?<=id=)[a-zA-Z0-9_-]*)|(?<=\\/file\\/d\\/)[a-zA-Z0-9_-]*");
var match = regex.Match(url);
return new State(match.ToString());
}
return null;
}
2019-12-07 02:45:13 +00:00
public async Task Prepare()
{
}
[JsonName("GoogleDriveDownloader")]
public class State : AbstractDownloadState
{
public string Id { get; }
2020-03-26 23:02:15 +00:00
[JsonIgnore]
public override object[] PrimaryKey => new object[] { Id };
public State(string id)
{
Id = id;
}
public override bool IsWhitelisted(ServerWhitelist whitelist)
{
return whitelist.GoogleIDs.Contains(Id);
}
2020-03-25 22:30:43 +00:00
public override async Task<bool> Download(Archive a, AbsolutePath destination)
{
2019-12-06 05:59:57 +00:00
var state = await ToHttpState();
return await state.Download(a, destination);
}
2019-12-06 05:59:57 +00:00
private async Task<HTTPDownloader.State> ToHttpState()
{
2019-11-21 15:51:57 +00:00
var initialURL = $"https://drive.google.com/uc?id={Id}&export=download";
2020-06-26 17:08:30 +00:00
var client = new Wabbajack.Lib.Http.Client();
using var response = await client.GetAsync(initialURL);
if (!response.IsSuccessStatusCode)
throw new HttpException((int)response.StatusCode, response.ReasonPhrase);
var regex = new Regex("(?<=/uc\\?export=download&amp;confirm=).*(?=;id=)");
var confirm = regex.Match(await response.Content.ReadAsStringAsync());
var url = $"https://drive.google.com/uc?export=download&confirm={confirm}&id={Id}";
var httpState = new HTTPDownloader.State(url) { Client = client };
2019-11-21 15:51:57 +00:00
return httpState;
}
public override async Task<bool> Verify(Archive a, CancellationToken? token)
{
2019-12-06 05:59:57 +00:00
var state = await ToHttpState();
return await state.Verify(a, token);
}
public override IDownloader GetDownloader()
{
return DownloadDispatcher.GetInstance<GoogleDriveDownloader>();
}
public override string GetManifestURL(Archive a)
{
return $"https://drive.google.com/uc?id={Id}&export=download";
}
public override string[] GetMetaIni()
{
return new [] {"[General]",$"directURL=https://drive.google.com/uc?id={Id}&export=download"};
}
}
}
}