Small Tweaks and changes

This commit is contained in:
Václav Španinger 2024-09-09 11:48:57 -07:00
parent e82472be0c
commit d66abc1f07
5 changed files with 275 additions and 27 deletions

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FakeeDeck.ButtonType
{
internal class Button
{
public static string getButton(string Key)
{
return
"<div class=\"m-2\">" +
" <form style=\"margin-bottom: 0px;\" method=\"post\" action=\"keyboard\\stratogem\">" +
" <input type=\"hidden\" name=\"stratogem\" value=>" +
" <input style=\"background-size: cover; ; width: 150px;height: 150px;background-color: aquamarine;\" type=\"submit\" value=\"\">" +
" </form>" +
"</div>";
}
public static bool invokeAction(string Key)
{
return false;
}
}
}

View File

@ -7,7 +7,7 @@ using static System.Net.WebRequestMethods;
namespace FakeeDeck.ButtonType
{
class HelldiversTwoMacro
class HelldiversTwoMacro : Button
{
//https://helldivers.wiki.gg/wiki/Stratagems
//https://helldivers.fandom.com/wiki/Stratagems_(Helldivers_2)
@ -51,19 +51,24 @@ namespace FakeeDeck.ButtonType
{
return
"<div class=\"m-2\">" +
" <form style=\"margin-bottom: 0px;\" method=\"post\" action=\"keyboard\\stratogem\">" +
" <form style=\"margin-bottom: 0px;\" method=\"post\" action=\"button\\HelldiversTwoMacro\">" +
" <input type=\"hidden\" name=\"stratogem\" value=\"" + Key + "\">" +
" <input style=\"background-image: url('" + stratogemsIcons[Key].ToString() + "'); width: 200px;height: 200px;background-color: aquamarine;\" type=\"submit\" value=\"" + FirstLetterToUpper(Key) + "\">" +
" <input style=\"background-size: cover; background-image: url('" + stratogemsIcons[Key].ToString() + "'); width: 150px;height: 150px;background-color: aquamarine;\" type=\"submit\" value=\"" + FirstLetterToUpper(Key) + "\">" +
" </form>" +
"</div>";
}
public static bool invokeAction(string Key)
public static bool invokeAction(string stratogem)
{
return false;
foreach (var key in stratogems[stratogem])
{
KeyboardMacro.SendKey(key);
Console.WriteLine(key);
}
return true;
}
public static string FirstLetterToUpper(string str)
private static string FirstLetterToUpper(string str)
{
if (str == null)
return null;

View File

@ -7,4 +7,14 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Folder Include="StaticFiles\" />
</ItemGroup>
<ItemGroup>
<None Update="StaticFiles\app.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -12,11 +12,83 @@ using System.Threading.Tasks;
using FakeeDeck.ButtonType;
using System.Web;
using static System.Net.WebRequestMethods;
using File = System.IO.File;
using System.Reflection.Metadata;
using System.Xml.Linq;
using System.Reflection;
using System.Text.Json;
namespace FakeeDeck
{
internal class HttpServer
{
private static IDictionary<string, string> mimeTypes = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
{".asf", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".cco", "application/x-cocoa"},
{".crt", "application/x-x509-ca-cert"},
{".css", "text/css"},
{".deb", "application/octet-stream"},
{".der", "application/x-x509-ca-cert"},
{".dll", "application/octet-stream"},
{".dmg", "application/octet-stream"},
{".ear", "application/java-archive"},
{".eot", "application/octet-stream"},
{".exe", "application/octet-stream"},
{".flv", "video/x-flv"},
{".gif", "image/gif"},
{".hqx", "application/mac-binhex40"},
{".htc", "text/x-component"},
{".htm", "text/html"},
{".html", "text/html"},
{".ico", "image/x-icon"},
{".img", "application/octet-stream"},
{".iso", "application/octet-stream"},
{".jar", "application/java-archive"},
{".jardiff", "application/x-java-archive-diff"},
{".jng", "image/x-jng"},
{".jnlp", "application/x-java-jnlp-file"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".mml", "text/mathml"},
{".mng", "video/x-mng"},
{".mov", "video/quicktime"},
{".mp3", "audio/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".msi", "application/octet-stream"},
{".msm", "application/octet-stream"},
{".msp", "application/octet-stream"},
{".pdb", "application/x-pilot"},
{".pdf", "application/pdf"},
{".pem", "application/x-x509-ca-cert"},
{".pl", "application/x-perl"},
{".pm", "application/x-perl"},
{".png", "image/png"},
{".prc", "application/x-pilot"},
{".ra", "audio/x-realaudio"},
{".rar", "application/x-rar-compressed"},
{".rpm", "application/x-redhat-package-manager"},
{".rss", "text/xml"},
{".run", "application/x-makeself"},
{".sea", "application/x-sea"},
{".shtml", "text/html"},
{".sit", "application/x-stuffit"},
{".swf", "application/x-shockwave-flash"},
{".tcl", "application/x-tcl"},
{".tk", "application/x-tcl"},
{".txt", "text/plain"},
{".war", "application/java-archive"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wmv", "video/x-ms-wmv"},
{".xml", "text/xml"},
{".xpi", "application/x-xpinstall"},
{".zip", "application/zip"},
};
public static HttpListener listener;
public static string url = "http://*:8000/";
public static int pageViews = 0;
@ -30,22 +102,23 @@ namespace FakeeDeck
" <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\">" +
" <link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css\" rel=\"stylesheet\">" +
" </head>" +
" <body>"+
" <body>" +
" <div class=\"d-flex flex-wrap\">" +
" <div class=\"m-2\">" +
" <p style=\"margin-bottom: 0px; width: 200px;height: 200px;background-color: aquamarine;\" >Page Views: {0}</p>" +
" <p style=\"margin-bottom: 0px; width: 150px;height: 150px;background-color: aquamarine;\" >Page Views: {0}</p>" +
" </div>";
public static string pageFooter =
" <div class=\"m-2\">" +
" <button style=\"width: 200px;height: 200px;background-color: aquamarine;\" onclick=\"!document.fullscreenElement ? document.documentElement.requestFullscreen() : document.exitFullscreen();\">"+
" <i class=\"fa-solid fa-maximize\"></i>"+
" <button style=\"width: 150px;height: 150px;background-color: aquamarine;\" onclick=\"!document.fullscreenElement ? document.documentElement.requestFullscreen() : document.exitFullscreen();\">" +
" <i class=\"fa-solid fa-maximize\"></i>" +
" </button>" +
" </div>"+
" </div>" +
" </div>" +
" <script src=\"StaticFiles/app.js\"></script>" +
" </body>" +
"</html>";
public static string pageData = "";
public static async Task HandleIncomingConnections()
@ -69,9 +142,10 @@ namespace FakeeDeck
Console.WriteLine(req.UserHostName);
Console.WriteLine(req.UserAgent);
Console.WriteLine();
Dictionary<string, string> postParams = new Dictionary<string, string>();
if(req.HttpMethod == "POST"){
if (req.HttpMethod == "POST")
{
using (var reader = new StreamReader(req.InputStream, req.ContentEncoding))
{
string postData = reader.ReadToEnd();
@ -91,25 +165,86 @@ namespace FakeeDeck
}
// If `shutdown` url requested w/ POST, then shutdown the server after serving the page
if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/keyboard/stratogem"))
if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath.StartsWith("/button")))
{
//new uint[] { 0x65, 0x68, 0x62, 0x66, 0x64, 0x68, 0x0D, 0x0D, }
foreach (var key in HelldiversTwoMacro.stratogems[postParams["stratogem"]])
try
{
KeyboardMacro.SendKey(key);
Console.WriteLine(key);
string module = req.Url.AbsolutePath.Replace("/button", "");
Console.WriteLine("Call module " + module);
Console.WriteLine(postParams["stratogem"]);
callButtonAction(module, postParams);
resp.StatusCode = (int)HttpStatusCode.OK;
}
resp.Redirect("/");
catch (Exception ex)
{
byte[] errorData = Encoding.UTF8.GetBytes(ex.Message);
resp.ContentType = "text/html";
resp.ContentEncoding = Encoding.UTF8;
resp.ContentLength64 = errorData.LongLength;
resp.StatusCode = (int)HttpStatusCode.InternalServerError;
await resp.OutputStream.WriteAsync(errorData, 0, errorData.Length);
}
finally
{
resp.Close();
}
continue;
}
if (req.Url.AbsolutePath.Contains("."))
{
string filename = Path.Combine("./", req.Url.AbsolutePath.Substring(1));
if (File.Exists(filename))
{
try
{
Stream input = new FileStream(filename, FileMode.Open);
string mime;
resp.ContentType = mimeTypes.TryGetValue(Path.GetExtension(filename), out mime)
? mime
: "application/octet-stream";
resp.ContentLength64 = input.Length;
resp.AddHeader("Date", DateTime.Now.ToString("r"));
resp.AddHeader("Last-Modified", File.GetLastWriteTime(filename).ToString("r"));
byte[] buffer = new byte[1024 * 32];
int nbytes;
while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
resp.OutputStream.Write(buffer, 0, nbytes);
input.Close();
resp.OutputStream.Flush();
resp.StatusCode = (int)HttpStatusCode.OK;
}
catch (Exception ex)
{
byte[] errorData = Encoding.UTF8.GetBytes(ex.Message);
resp.ContentType = "text/html";
resp.ContentEncoding = Encoding.UTF8;
resp.ContentLength64 = errorData.LongLength;
resp.StatusCode = (int)HttpStatusCode.InternalServerError;
await resp.OutputStream.WriteAsync(errorData, 0, errorData.Length);
}
finally
{
resp.Close();
}
continue;
}
}
// Make sure we don't increment the page views counter if `favicon.ico` is requested
if (req.Url.AbsolutePath != "/favicon.ico")
{
pageViews += 1;
}
// Write the response info
string disableSubmit = !runServer ? "disabled" : "";
byte[] data = Encoding.UTF8.GetBytes(String.Format((pageHeader + pageData + pageFooter), pageViews, disableSubmit));
@ -123,7 +258,6 @@ namespace FakeeDeck
}
}
public static void serv()
{
foreach (var stratogem in HelldiversTwoMacro.stratogems)
@ -131,9 +265,8 @@ namespace FakeeDeck
pageData += HelldiversTwoMacro.getButton(stratogem.Key);
}
// Create a Http server and start listening for incoming connections
listener = new HttpListener();
// Create a Http server and start listening for incoming connections
listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
Console.WriteLine("Listening for connections on {0}", url);
@ -146,6 +279,41 @@ namespace FakeeDeck
listener.Close();
}
private static void callButtonAction(string module, Dictionary<string, string> postParams)
{
string cleanClass = module.Trim('/');
Type buttonClass = Type.GetType("FakeeDeck.ButtonType." + cleanClass, true);
MethodInfo method = buttonClass.GetMethod("invokeAction");
ParameterInfo[] pars = method.GetParameters();
List<object> parameters = new List<object>();
Console.WriteLine(module);
foreach (ParameterInfo p in pars)
{
if (p == null)
{
continue;
}
Console.WriteLine(p.Name);
Console.WriteLine(postParams[p.Name]);
if (p.Name != null && postParams.ContainsKey(p.Name))
{
parameters.Insert(p.Position, postParams[p.Name]);
Console.WriteLine(postParams[p.Name]);
}
else if (p.IsOptional && p.DefaultValue != null)
{
parameters.Insert(p.Position, p.DefaultValue);
}
}
Console.WriteLine(JsonSerializer.Serialize(parameters));
Console.WriteLine(method);
Console.WriteLine(method.Invoke(null, parameters.ToArray()).ToString());
}
}
}

View File

@ -0,0 +1,38 @@
[].forEach.call(document.querySelectorAll('form'), function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
const target = event.currentTarget;
console.log(target.method, target.action);
console.log(form.method, form.action);
console.log(form === target);
var formData = new FormData(form);
const xhttp = new XMLHttpRequest();
xhttp.onload = function () { }
xhttp.onreadystatechange = function () {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
console.log('successful');
} else {
console.log('failed');
}
}
}
xhttp.open(target.method, target.action, true);
xhttp.send(urlencodeFormData(formData));
});
});
function urlencodeFormData(fd){
var s = '';
function encode(s){ return encodeURIComponent(s).replace(/%20/g,'+'); }
for(var pair of fd.entries()){
if(typeof pair[1]=='string'){
s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
}
}
return s;
}