http client with cache

This commit is contained in:
HolographicHat
2022-06-13 22:22:40 +08:00
parent bbe7c2cd03
commit 1dcaf7ed8f
6 changed files with 432 additions and 4 deletions

View File

@@ -7,6 +7,8 @@
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationManifest>res\app.manifest</ApplicationManifest>
<AssemblyVersion>2.0.0</AssemblyVersion>
<FileVersion>2.0.0</FileVersion>
</PropertyGroup>
<ItemGroup>

View File

@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace YaeAchievement;
@@ -10,9 +11,11 @@ public static class GlobalVars {
public static bool Verbose = false;
public static bool UnexpectedExit = true;
public static string GamePath = "";
public static Version AppVersion = Assembly.GetEntryAssembly()!.GetName().Version!;
public const string LibName = "YaeLib.dll";
public const string PipeName = "YaeAchievementPipe";
public const string BucketHost = "https://cn-cd-1259389942.file.myqcloud.com";
public const string ConfigFileName = "YaeAchievement.runtimeconfig.json";
}

5
src/Logger.cs Normal file
View File

@@ -0,0 +1,5 @@
namespace YaeAchievement;
public static class Logger {
}

View File

@@ -1,10 +1,14 @@
using YaeAchievement;
using System.Net;
using System.Net.Http.Headers;
using YaeAchievement;
using static YaeAchievement.Utils;
InstallExitHook();
/*InstallExitHook();
InstallExceptionHook();
CheckGenshinIsRunning();
LoadConfig();
LoadConfig();*/
var ch = GetBucketFileAsString("latest.json");
//Console.WriteLine(c.Send(msg).StatusCode);
return;
StartAndWaitResult(@"D:\Genshin Impact Dev\2.8\YuanShen.exe", str => {
GlobalVars.UnexpectedExit = false;

341
src/Proto/CacheItem.cs Normal file
View File

@@ -0,0 +1,341 @@
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: CacheItem.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021, 8981
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
/// <summary>Holder for reflection information generated from CacheItem.proto</summary>
public static partial class CacheItemReflection {
#region Descriptor
/// <summary>File descriptor for CacheItem.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CacheItemReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cg9DYWNoZUl0ZW0ucHJvdG8iTQoJQ2FjaGVJdGVtEg8KB3ZlcnNpb24YASAB",
"KAUSEAoIY2hlY2tzdW0YAiABKAkSDAoEZXRhZxgDIAEoCRIPCgdjb250ZW50",
"GAQgASgMYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::CacheItem), global::CacheItem.Parser, new[]{ "Version", "Checksum", "Etag", "Content" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class CacheItem : pb::IMessage<CacheItem>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<CacheItem> _parser = new pb::MessageParser<CacheItem>(() => new CacheItem());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<CacheItem> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::CacheItemReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CacheItem() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CacheItem(CacheItem other) : this() {
version_ = other.version_;
checksum_ = other.checksum_;
etag_ = other.etag_;
content_ = other.content_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CacheItem Clone() {
return new CacheItem(this);
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 1;
private int version_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Version {
get { return version_; }
set {
version_ = value;
}
}
/// <summary>Field number for the "checksum" field.</summary>
public const int ChecksumFieldNumber = 2;
private string checksum_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Checksum {
get { return checksum_; }
set {
checksum_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "etag" field.</summary>
public const int EtagFieldNumber = 3;
private string etag_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Etag {
get { return etag_; }
set {
etag_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "content" field.</summary>
public const int ContentFieldNumber = 4;
private pb::ByteString content_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pb::ByteString Content {
get { return content_; }
set {
content_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as CacheItem);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(CacheItem other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Version != other.Version) return false;
if (Checksum != other.Checksum) return false;
if (Etag != other.Etag) return false;
if (Content != other.Content) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Version != 0) hash ^= Version.GetHashCode();
if (Checksum.Length != 0) hash ^= Checksum.GetHashCode();
if (Etag.Length != 0) hash ^= Etag.GetHashCode();
if (Content.Length != 0) hash ^= Content.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Version != 0) {
output.WriteRawTag(8);
output.WriteInt32(Version);
}
if (Checksum.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Checksum);
}
if (Etag.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Etag);
}
if (Content.Length != 0) {
output.WriteRawTag(34);
output.WriteBytes(Content);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Version != 0) {
output.WriteRawTag(8);
output.WriteInt32(Version);
}
if (Checksum.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Checksum);
}
if (Etag.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Etag);
}
if (Content.Length != 0) {
output.WriteRawTag(34);
output.WriteBytes(Content);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Version != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Version);
}
if (Checksum.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Checksum);
}
if (Etag.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Etag);
}
if (Content.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Content);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(CacheItem other) {
if (other == null) {
return;
}
if (other.Version != 0) {
Version = other.Version;
}
if (other.Checksum.Length != 0) {
Checksum = other.Checksum;
}
if (other.Etag.Length != 0) {
Etag = other.Etag;
}
if (other.Content.Length != 0) {
Content = other.Content;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Version = input.ReadInt32();
break;
}
case 18: {
Checksum = input.ReadString();
break;
}
case 26: {
Etag = input.ReadString();
break;
}
case 34: {
Content = input.ReadBytes();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Version = input.ReadInt32();
break;
}
case 18: {
Checksum = input.ReadString();
break;
}
case 26: {
Etag = input.ReadString();
break;
}
case 34: {
Content = input.ReadBytes();
break;
}
}
}
}
#endif
}
#endregion
#endregion Designer generated code

View File

@@ -1,8 +1,14 @@
using System.ComponentModel;
using System.Diagnostics;
using System.IO.Compression;
using System.IO.Pipes;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using Google.Protobuf;
using YaeAchievement.Win32;
using static YaeAchievement.Win32.OpenFileFlags;
@@ -10,7 +16,72 @@ namespace YaeAchievement;
public static class Utils {
private static readonly Lazy<HttpClient> CHttpClient = new (() => {
var c = new HttpClient(new HttpClientHandler {
Proxy = new WebProxy("http://127.0.0.1:8888")
}) {
DefaultRequestHeaders = {
UserAgent = {
new ProductInfoHeaderValue("YaeAchievement", GlobalVars.AppVersion.ToString(2))
}
}
};
return c;
});
public static string GetBucketFileAsString(string path) {
return Encoding.UTF8.GetString(GetBucketFileAsByteArray(path));
}
public static byte[] GetBucketFileAsByteArray(string path) {
using var msg = new HttpRequestMessage {
Method = HttpMethod.Get,
RequestUri = new Uri($"{GlobalVars.BucketHost}/{path}")
};
CacheItem? ci = null;
string? etag = null;
var cacheName = $"./cache/{CalculateMD5(path)[..16]}.miko";
if (File.Exists(cacheName)) {
using var input = File.OpenRead(cacheName);
using var dInput = new GZipStream(input, CompressionMode.Decompress);
ci = CacheItem.Parser.ParseFrom(dInput);
etag = ci.Etag;
}
if (etag != null) {
msg.Headers.TryAddWithoutValidation("If-None-Match", $"{etag}");
}
using var response = CHttpClient.Value.Send(msg);
if (response.StatusCode == HttpStatusCode.NotModified) {
return ci!.Content.ToByteArray();
}
response.EnsureSuccessStatusCode();
etag = response.Headers.ETag!.Tag;
var responseBytes = response.Content.ReadAsByteArrayAsync().Result;
using var os = File.OpenWrite(cacheName);
using var cos = new GZipStream(os, CompressionLevel.SmallestSize);
new CacheItem {
Etag = etag,
Version = 3,
Checksum = CalculateMD5(responseBytes),
Content = ByteString.CopyFrom(responseBytes)
}.WriteTo(cos);
return responseBytes;
}
// ReSharper disable once InconsistentNaming
private static string CalculateMD5(string text) {
return CalculateMD5(Encoding.UTF8.GetBytes(text));
}
// ReSharper disable once InconsistentNaming
private static string CalculateMD5(byte[] bytes) {
using var md5 = MD5.Create();
var b = md5.ComputeHash(bytes);
return Convert.ToHexString(b).ToLower();
}
public static void LoadConfig() {
Directory.CreateDirectory("cache");
var conf = JsonNode.Parse(File.ReadAllText(GlobalVars.ConfigFileName))!;
var path = conf["genshinPath"];
if (path == null || CheckGamePathValid(path.GetValue<string>())) {
@@ -112,7 +183,9 @@ public static class Utils {
while (!proc.HasExited) {
var line = reader.ReadLine();
if (line?.Length > 0) {
if (onReceive(line)) break;
if (onReceive(line)) {
break;
}
server.Disconnect();
server.WaitForConnection();
}