Skip to content

Commit

Permalink
Use WebResourceRequested to load resources
Browse files Browse the repository at this point in the history
  • Loading branch information
hbl917070 committed Dec 17, 2024
1 parent 7e52334 commit 00fcc0c
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 29 deletions.
4 changes: 2 additions & 2 deletions Tiefsee/Server/WebServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ private async void GetContextCallBack(IAsyncResult ar) {
string url = request.Url.ToString();
url = url.Substring(baseUrl.Length);

var origin = request.Headers.Get("origin");
/* var origin = request.Headers.Get("origin");
// UserAgent 裡面不包含 "Tiefsee",就回傳 403
if (request?.UserAgent.Contains(Program.webvviewUserAgent) == false) {
Expand All @@ -73,7 +73,7 @@ private async void GetContextCallBack(IAsyncResult ar) {
context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length);
context.Response.Close();
return;
}
} */

// 允許任何來自任何網域的請求
// context.Response.AddHeader("Access-Control-Allow-Origin", "*");
Expand Down
6 changes: 3 additions & 3 deletions Tiefsee/Server/WebServerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -909,7 +909,7 @@ await WriteJson(d,

#region Headers 相關

/// <summary>
/// <summary>
/// 回傳檔案時加入快取的 Headers
/// </summary>
/// <returns> true=304 false=正常回傳檔案 </returns>
Expand Down Expand Up @@ -1031,12 +1031,12 @@ private async Task WriteStream(RequestData d, Stream ms) {
#endregion

// 取得檔案的 MIME type
private string GetMimeTypeMapping(string path) {
public static string GetMimeTypeMapping(string path) {
return _mimeTypeMappings.TryGetValue(Path.GetExtension(path), out string mime) ?
mime :
"application/octet-stream";
}
private IDictionary<string, string> _mimeTypeMappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
private static IDictionary<string, string> _mimeTypeMappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
#region extension to MIME type list
{".asf", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
Expand Down
25 changes: 15 additions & 10 deletions Tiefsee/VW/WV_RunApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,18 +148,23 @@ public List<UwpItem> GetUwpList() {

// 如果暫存不存在此筆資料,則重新抓資料
if (_tempUwpItem.ContainsKey(fullName) == false) {
string name = package.DisplayName; // APP在地化的名稱 (取得成本高)
string logo = package.Logo.ToString(); // 圖示的路徑 (取得成本高)
string id = package.Id.Name + "_" + package.Id.PublisherId;
// 忽略異常的資料
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(logo) || string.IsNullOrEmpty(id)) {
try {
string name = package.DisplayName; // APP在地化的名稱 (取得成本高)
string logo = package.Logo.ToString(); // 圖示的路徑 (取得成本高)
string id = package.Id.Name + "_" + package.Id.PublisherId;
// 忽略異常的資料
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(logo) || string.IsNullOrEmpty(id)) {
continue;
}
_tempUwpItem.Add(fullName, new UwpItem {
Logo = logo,
Name = name,
Id = id
});
}
catch {
continue;
}
_tempUwpItem.Add(fullName, new UwpItem {
Logo = logo,
Name = name,
Id = id
});
}

if (isFirstRun) {
Expand Down
53 changes: 47 additions & 6 deletions Tiefsee/WebWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ void Wv2LoadedTriggerCreate(WebWindow ww, string[] args) {
TriggerCreate(ww, args);

ww._wv2.CoreWebView2.DOMContentLoaded += (sender, e) => {
if (_isEventTriggered) { return; }
// if (_isEventTriggered) { return; }

TriggerCreate(ww, args);
_isEventTriggered = true;
Expand Down Expand Up @@ -209,10 +209,10 @@ void Wv2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEvent
/// </summary>
private static string GetHtmlFilePath(string fileName) {
/* return "file:///" +
Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Www", fileName) +
"#" + Program.webServer.port; // port 用於讓 js 識別 webAPI 的網址 */
// return $"http://tiefsee.com/www/{fileName}#{Program.webServer.port}";
return $"http:127.0.0.1:{Program.webServer.port}/www/{fileName}#{Program.webServer.port}";
Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Www", fileName) +
"#" + Program.webServer.port; // port 用於讓 js 識別 webAPI 的網址 */
return $"http://app.example/{fileName}#{Program.webServer.port}";
// return $"http:127.0.0.1:{Program.webServer.port}/www/{fileName}#{Program.webServer.port}";
}

/// <summary>
Expand Down Expand Up @@ -306,7 +306,7 @@ public static async Task<CoreWebView2Environment> GetCoreWebView2Environment() {
// --disable-features=msWebOOUI,msPdfOOUI 禁止迷你選單
// --user-agent 覆寫userAgent
// --enable-features=msWebView2EnableDraggableRegions 讓 webview2 支援 css「app-region:drag」
string webvviewArguments = null;
string webvviewArguments = "--disable-web-security";
var opts = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = webvviewArguments };
_webView2Environment = await CoreWebView2Environment.CreateAsync(null, AppPath.appData, opts);
}
Expand Down Expand Up @@ -388,6 +388,47 @@ public async Task Init() {
.CreateWebResourceResponse(null, 200, "OK", "");
};

_wv2.CoreWebView2.AddWebResourceRequestedFilter("http://app.example/*", CoreWebView2WebResourceContext.All);
_wv2.CoreWebView2.WebResourceRequested += delegate (object sender, CoreWebView2WebResourceRequestedEventArgs args) {

var url = args.Request.Uri.Substring("http://app.example/*".Length - 1);

// 去掉?與 # 後面的字串
int index = url.IndexOf("?");
if (index != -1) { url = url.Substring(0, index); }
index = url.IndexOf("#");
if (index != -1) { url = url.Substring(0, index); }

string assetsFilePath;
if (url.ToLower().StartsWith("plugin/")) {
url = url.Substring(7);

assetsFilePath = System.IO.Path.Combine(
AppPath.appDataPlugin, url);
}
else {
if (url.ToLower().StartsWith("www/")) {
url = url.Substring(5);
}
assetsFilePath = System.IO.Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory, "Www", url);
}

assetsFilePath = Path.GetFullPath(assetsFilePath);

try {
var ext = Path.GetExtension(assetsFilePath).ToLower();
var headers = "Content-Type: " + WebServerController.GetMimeTypeMapping(ext);
var fs = File.OpenRead(assetsFilePath);
args.Response = _wv2.CoreWebView2.Environment.CreateWebResourceResponse(
fs, 200, "OK", headers);
}
catch {
args.Response = _wv2.CoreWebView2.Environment.CreateWebResourceResponse(
null, 404, "Not found", "");
}
};

WV_Window = new WV_Window(this);
WV_Directory = new WV_Directory(this);
WV_File = new WV_File(this);
Expand Down
2 changes: 1 addition & 1 deletion Www/iframe/CherryMarkdown.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
window.addEventListener("message", (e) => {

// 只開放特定網域呼叫
if (e.origin !== libIframe.APIURL) {
if (e.origin !== libIframe.APIURL && e.origin !== location.origin) {
console.error("錯誤的請求來源:" + e.origin);
return;
}
Expand Down
2 changes: 1 addition & 1 deletion Www/iframe/MonacoEditor.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
window.addEventListener("message", (e) => {

// 只開放特定網域呼叫
if (e.origin !== libIframe.APIURL) {
if (e.origin !== libIframe.APIURL && e.origin !== location.origin) {
console.error("錯誤的請求來源:" + e.origin)
return;
}
Expand Down
2 changes: 1 addition & 1 deletion Www/iframe/PDFTronWebviewer.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
window.addEventListener("message", (e) => {

// 只開放特定網域呼叫
if (e.origin !== libIframe.APIURL) {
if (e.origin !== libIframe.APIURL && e.origin !== location.origin) {
console.error("錯誤的請求來源:" + e.origin)
return;
}
Expand Down
3 changes: 2 additions & 1 deletion Www/ts/LibIframe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ class LibIframe {
* 取得 Plugin 的路徑
*/
public getPluginPath() {
return this.APIURL + "/Plugin";
// return this.APIURL + "/Plugin";
return "/plugin";
}

/**
Expand Down
8 changes: 4 additions & 4 deletions Www/ts/MainWindow/Iframes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class Iframes {
window.addEventListener("message", async (e) => {

// 只開放特定網域呼叫
if (e.origin !== APIURL) {
if (e.origin !== APIURL && e.origin !== location.origin) {
console.error("錯誤的請求來源:" + e.origin)
return;
}
Expand Down Expand Up @@ -153,7 +153,7 @@ class PdfTronWebviewer {
window.addEventListener("message", (e) => {

// 只開放特定網域呼叫
if (e.origin !== APIURL) {
if (e.origin !== APIURL && e.origin !== location.origin) {
console.error("錯誤的請求來源:" + e.origin)
return;
}
Expand Down Expand Up @@ -260,7 +260,7 @@ class MonacoEditor {
window.addEventListener("message", (e) => {

// 只開放特定網域呼叫
if (e.origin !== APIURL) {
if (e.origin !== location.origin) {
console.error("錯誤的請求來源:" + e.origin)
return;
}
Expand Down Expand Up @@ -412,7 +412,7 @@ class CherryMarkdown {
window.addEventListener("message", (e) => {

// 只開放特定網域呼叫
if (e.origin !== APIURL) {
if (e.origin !== APIURL && e.origin !== location.origin) {
console.error("錯誤的請求來源:" + e.origin)
return;
}
Expand Down

0 comments on commit 00fcc0c

Please sign in to comment.