Skip to content

Commit

Permalink
misc: 处理gosu文件请求时直接从目录寻找文件
Browse files Browse the repository at this point in the history
  • Loading branch information
MATRIX-feather committed Jul 22, 2024
1 parent 6287198 commit 289cbe3
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,30 +67,24 @@ private void setupGosuStatics(WebSocketLoader.GosuServer server)
Logging.Log("Setting up statics...");

var staticsStorage = globalStorage.GetStorageForDirectory("gosu_statics");
string? staticPath = staticsStorage.GetFullPath(".");
string? staticPath = staticsStorage.GetFullPath(".", true);

if (staticPath == null || !Directory.Exists(staticPath))
{
Logging.Log("Null static path or it doesn't exists!");
return;
}

server.SetStorage(globalStorage);
var cacheStorage = globalStorage.GetStorageForDirectory("gosu_caches");
string? cachePath = cacheStorage.GetFullPath(".", true);

DirectoryInfo dirInfo = new DirectoryInfo(staticPath);

if (!dirInfo.Exists)
if (cachePath == null || !Directory.Exists(cachePath))
{
var newDirInfo = Directory.CreateDirectory(staticPath);

if (!newDirInfo.Exists)
{
Logging.Log("Unable to create statics directory, skipping...");
return;
}
Logging.Log("Cache directory is null or non-exist!");
return;
}

server.AddStaticContent(staticPath);
server.SetStorage(globalStorage, cacheStorage);
Logging.Log("Done setting up static content!");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,6 @@ private void updateFileSupporters(BeatmapSetInfo setInfo, WorkingBeatmap beatmap
beatmap.BeatmapInfo.BeatmapSet?.Metadata.AudioFile ?? "",
audioFileDesti).ConfigureAwait(false);

// Await for statics refresh
await Task.Run(updateStatics).ConfigureAwait(false);

// Update!
this.Schedule(() =>
{
Expand Down Expand Up @@ -280,9 +277,6 @@ private void clearCache(string cacheRoot)

foreach (var fileInfo in dirInfo.GetFiles())
fileInfo.Delete();

var server = Hub.GetWsLoader()?.Server;
server?.ClearStaticContent();
}
catch (Exception e)
{
Expand All @@ -295,18 +289,4 @@ private Guid genGuidFrom(string str)
byte[] hash = MD5.HashData(Encoding.Unicode.GetBytes(str));
return new Guid(hash);
}

private void updateStatics()
{
try
{
var server = Hub.GetWsLoader()?.Server;
server?.ClearStaticContent();
server?.AddStaticContent(staticRoot(), "/Songs");
}
catch (Exception e)
{
Logging.LogError(e, "Unable to add cache");
}
}
}
67 changes: 63 additions & 4 deletions osu.Game.Rulesets.IGPlayer/Feature/Gosumemory/Web/GosuSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ protected override void OnReceivedRequest(HttpRequest request)
if (!path.EndsWith("/ws", StringComparison.Ordinal)
&& !path.EndsWith("/json", StringComparison.Ordinal))
{
Logging.Log("Received FILE? request " + request.Url);

HttpResponse response = new HttpResponse();
response.SetBegin(200);

Expand Down Expand Up @@ -66,17 +68,70 @@ protected override void OnReceivedRequest(HttpRequest request)
string storagePath = Path.Combine("gosu_statics", urlPath);

// 目标存储的绝对位置
string targetLocalStorage = storage.GetFullPath(storagePath);
string targetFilePath = storage.GetFullPath(storagePath);

Logging.Log("URLPath is " + urlPath);

// 处理Songs
if (urlPath.StartsWith("Songs", StringComparison.Ordinal))
{
string[] split = urlPath.Split("/", 2);
var fileResponse = new HttpResponse();

if (split.Length < 2)
{
Logging.Log("Illegal argument, not processing...");
fileResponse.SetBegin(400);
this.SendResponse(fileResponse);

return;
}

string fileName = split[1].Split("?", 2)[0];

byte[] content = gosuServer.FindStaticOrAsset(fileName) ?? new byte[] { };

if (content.Length == 0)
{
response.SetBegin(404);
this.SendResponse(response);

return;
}

fileResponse.SetBegin(200);
response.SetHeader("Cache-Control", stringAndClear)
.SetHeader("Access-Control-Allow-Origin", "*");
response.SetBody(content);

this.SendResponse(response);
return;
}

// 如果要访问文件, 那么不要进行处理
if (File.Exists(targetLocalStorage))
if (File.Exists(targetFilePath))
{
base.OnReceivedRequest(request);
var fileResponse = new HttpResponse();
byte[] content = gosuServer.FindStaticOrAsset(targetFilePath) ?? new byte[] { };

if (content.Length == 0)
{
fileResponse.SetBegin(404);
this.SendResponse(response);
return;
}

fileResponse.SetBegin(200);
response.SetHeader("Cache-Control", stringAndClear)
.SetHeader("Access-Control-Allow-Origin", "*");
response.SetBody(File.ReadAllBytes(targetFilePath));

this.SendResponse(response);
return;
}

// 只当目录存在时遍历其中的内容
if (Path.Exists(targetLocalStorage))
if (Path.Exists(targetFilePath))
{
try
{
Expand Down Expand Up @@ -107,9 +162,13 @@ protected override void OnReceivedRequest(HttpRequest request)

response.SetBody(htmlCode);
this.SendResponse(response);

Logging.Log("Sending " + response.Body);
}
else
{
Logging.Log("Received WS OR JSON request " + request.Url);

base.OnReceivedRequest(request);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using NetCoreServer;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
Expand Down Expand Up @@ -106,23 +106,56 @@ protected override void Dispose(bool isDisposing)

public GosuServer? Server;

public partial class AssetManager
{
private readonly List<Storage> storages = new List<Storage>();

public AssetManager(List<Storage> storages)
{
SetStorages(storages);
}

public void SetStorages(List<Storage> newList)
{
storages.Clear();
storages.AddRange(newList);
}

public byte[] FindAsset(string relativePath)
{
foreach (var storage in storages)
{
if (!storage.Exists(relativePath)) continue;

string fullPath = storage.GetFullPath(relativePath);
return File.ReadAllBytes(fullPath);
}

return [];
}
}

public partial class GosuServer : WsServer
{
public GosuServer(IPAddress address, int port)
: base(address, port)
{
}

private Storage? storage;
public readonly AssetManager AssetManager = new AssetManager(new List<Storage>());

public void SetStorage(Storage storage)
private Storage staticsStorage;

public void SetStorage(Storage statics, Storage caches)
{
this.storage = storage;
this.staticsStorage = statics;

AssetManager.SetStorages([statics, caches]);
}

public Storage? GetStorage()
{
return this.storage;
return this.staticsStorage;
}

protected override TcpSession CreateSession() { return new GosuSession(this); }
Expand All @@ -138,32 +171,14 @@ public void AddCustomHandler(string path, string urlPath, FileCache.InsertHandle
this.Cache.InsertPath(path, urlPath, "*.*", timeout, handler);
}

/**
* From decompiled HttpServer#AddStaticContent(...)
*/
public new void AddStaticContent(string path, string prefix = "/", string filter = "*.*", TimeSpan? timeout = null)
public byte[]? FindStaticOrAsset(string path)
{
timeout ??= TimeSpan.FromHours(1.0);

this.Cache.InsertPath(path, prefix, filter, timeout.Value, handler);

static bool handler(FileCache cache, string key, byte[] value, TimeSpan timespan)
{
var response = new HttpResponse();
response.SetBegin(200);
response.SetContentType(Path.GetExtension(key));

var interpolatedStringHandler = new DefaultInterpolatedStringHandler(8, 1);
interpolatedStringHandler.AppendLiteral("max-age=");
interpolatedStringHandler.AppendFormatted(timespan.Seconds);

string stringAndClear = interpolatedStringHandler.ToStringAndClear();
response.SetHeader("Cache-Control", stringAndClear);
response.SetHeader("Access-Control-Allow-Origin", "*");
response.SetBody(value);
return this.AssetManager.FindAsset(path);
}

return cache.Add(key, response.Cache.Data, timespan);
}
public new void AddStaticContent(string path, string prefix = "/", string filter = "*.*", TimeSpan? timeout = null)
{
throw new Exception("Deprecated operation");
}
}
}
Expand Down

0 comments on commit 289cbe3

Please sign in to comment.