main: Added popup window and account login

This commit is contained in:
Nathan Woodburn 2023-06-06 17:14:26 +10:00
parent 1e10f4763f
commit aa7078fc99
Signed by: nathanwoodburn
GPG Key ID: 203B000478AD0EF1
5 changed files with 493 additions and 30 deletions

View File

@ -36,7 +36,7 @@
panelaccount = new Panel();
groupBoxaccount = new GroupBox();
label1 = new Label();
comboBoxusername = new ComboBox();
comboBoxaccount = new ComboBox();
textBoxaccountpassword = new TextBox();
buttonaccountlogin = new Button();
labelaccountpassword = new Label();
@ -91,7 +91,7 @@
// groupBoxaccount
//
groupBoxaccount.Controls.Add(label1);
groupBoxaccount.Controls.Add(comboBoxusername);
groupBoxaccount.Controls.Add(comboBoxaccount);
groupBoxaccount.Controls.Add(textBoxaccountpassword);
groupBoxaccount.Controls.Add(buttonaccountlogin);
groupBoxaccount.Controls.Add(labelaccountpassword);
@ -117,12 +117,12 @@
//
// comboBoxusername
//
comboBoxusername.FlatStyle = FlatStyle.Popup;
comboBoxusername.FormattingEnabled = true;
comboBoxusername.Location = new Point(97, 67);
comboBoxusername.Name = "comboBoxusername";
comboBoxusername.Size = new Size(190, 23);
comboBoxusername.TabIndex = 6;
comboBoxaccount.FlatStyle = FlatStyle.Popup;
comboBoxaccount.FormattingEnabled = true;
comboBoxaccount.Location = new Point(97, 67);
comboBoxaccount.Name = "comboBoxusername";
comboBoxaccount.Size = new Size(190, 23);
comboBoxaccount.TabIndex = 6;
//
// textBoxaccountpassword
//
@ -141,6 +141,7 @@
buttonaccountlogin.TabIndex = 3;
buttonaccountlogin.Text = "Login";
buttonaccountlogin.UseVisualStyleBackColor = true;
buttonaccountlogin.Click += LoginClick;
//
// labelaccountpassword
//
@ -206,7 +207,7 @@
private Label labelaccountpassword;
private GroupBox groupBoxaccount;
private Label label1;
private ComboBox comboBoxusername;
private ComboBox comboBoxaccount;
private TextBox textBoxaccountpassword;
}
}

View File

@ -1,3 +1,4 @@
using System.Net.Http;
using System.Runtime.InteropServices;
using Newtonsoft.Json.Linq;
@ -10,6 +11,8 @@ namespace FireWallet
Dictionary<string, string> nodeSettings;
Dictionary<string, string> theme;
int Network;
string account;
string password;
#endregion
#region Application
@ -301,31 +304,57 @@ namespace FireWallet
private async void GetAccounts()
{
await APIGet("wallet", true);
comboBoxusername.Items.Clear();
string APIresponse = await APIGet("wallet", true);
comboBoxaccount.Items.Clear();
if (APIresponse != "Error")
{
JArray jArray = JArray.Parse(APIresponse);
foreach (string account in jArray)
{
comboBoxusername.Items.Add(account);
comboBoxaccount.Items.Add(account);
}
if (comboBoxusername.Items.Count > 0)
if (comboBoxaccount.Items.Count > 0)
{
comboBoxusername.SelectedIndex = 0;
comboBoxaccount.SelectedIndex = 0;
}
else
{
comboBoxusername.Items.Add("No accounts found");
comboBoxusername.Enabled = false;
comboBoxaccount.Items.Add("No accounts found");
comboBoxaccount.Enabled = false;
}
}
else
{
comboBoxusername.Items.Add("No accounts found");
comboBoxusername.Enabled = false;
comboBoxaccount.Items.Add("No accounts found");
comboBoxaccount.Enabled = false;
}
}
private async Task<bool> Login()
{
string path = "wallet/" + account + "/unlock";
string content = "{\"passphrase\": \"" + password + "\",\"timeout\": 60}";
string APIresponse = await APIPost(path, true, content);
if (APIresponse.Contains("true"))
{
MessageBox.Show(APIresponse);
AddLog("Login success");
return true;
}
else
{
AddLog("Login failed");
NotifyForm notifyForm = new NotifyForm("Login Failed\nMake sure your password is correct");
notifyForm.ShowDialog();
notifyForm.Dispose();
return false;
}
return false;
}
#endregion
@ -335,7 +364,7 @@ namespace FireWallet
NodeStatus();
}
#region API
string APIresponse;
HttpClient httpClient = new HttpClient();
private async void NodeStatus()
{
// This will curl the below URL and return the result
@ -373,11 +402,38 @@ namespace FireWallet
toolStripStatusLabelstatus.Text = "Status: Node Not Connected";
}
}
private async Task APIGet(string path, bool wallet)
{
// This will curl the below URL and return the result
//curl http://x:api-key@127.0.0.1:12039/wallet/$id/account
private async Task<string> APIPost(string path, bool wallet, string content)
{
string key = nodeSettings["Key"];
string ip = nodeSettings["IP"];
string port = "1203";
if (Network == 1)
{
port = "1303";
}
if (wallet) port = port + "9";
else port = port + "7";
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "http://" + ip + ":" + port + "/" + path);
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("x:" + key)));
req.Content = new StringContent(content);
// Send request
HttpResponseMessage resp = await httpClient.SendAsync(req);
try {
resp.EnsureSuccessStatusCode();
}
catch
{
return "Error";
}
return await resp.Content.ReadAsStringAsync();
}
private async Task<string> APIGet(string path, bool wallet)
{
string key = nodeSettings["Key"];
string ip = nodeSettings["IP"];
@ -389,10 +445,6 @@ namespace FireWallet
if (wallet) port = port + "9";
else port = port + "7";
// Create HTTP client
HttpClient httpClient = new HttpClient();
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://" + ip + ":" + port + "/" + path);
@ -401,16 +453,23 @@ namespace FireWallet
// Send request and log response
HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
APIresponse = await response.Content.ReadAsStringAsync();
return await response.Content.ReadAsStringAsync();
}
// Log errors to log textbox
catch (Exception ex)
{
AddLog("Error: " + ex.Message);
APIresponse = "Error";
return "Error";
}
}
#endregion
private async void LoginClick(object sender, EventArgs e)
{
account = comboBoxaccount.Text;
password = textBoxaccountpassword.Text;
await Login();
}
}
}

76
FireWallet/NotifyForm.Designer.cs generated Normal file
View File

@ -0,0 +1,76 @@
namespace FireWallet
{
partial class NotifyForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
labelmessage = new Label();
button1 = new Button();
SuspendLayout();
//
// labelmessage
//
labelmessage.Dock = DockStyle.Fill;
labelmessage.Font = new Font("Segoe UI", 15F, FontStyle.Regular, GraphicsUnit.Point);
labelmessage.Location = new Point(0, 0);
labelmessage.Name = "labelmessage";
labelmessage.Size = new Size(382, 170);
labelmessage.TabIndex = 0;
labelmessage.Text = "Message";
labelmessage.TextAlign = ContentAlignment.TopCenter;
//
// button1
//
button1.Font = new Font("Segoe UI", 15F, FontStyle.Regular, GraphicsUnit.Point);
button1.Location = new Point(271, 120);
button1.Name = "button1";
button1.Size = new Size(99, 38);
button1.TabIndex = 1;
button1.Text = "Ok";
button1.UseVisualStyleBackColor = true;
button1.Click += button1_Click;
//
// NotifyForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(382, 170);
Controls.Add(button1);
Controls.Add(labelmessage);
FormBorderStyle = FormBorderStyle.FixedDialog;
Name = "NotifyForm";
Text = "FireWallet";
Load += NotifyForm_Load;
ResumeLayout(false);
}
#endregion
private Label labelmessage;
private Button button1;
}
}

207
FireWallet/NotifyForm.cs Normal file
View File

@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FireWallet
{
public partial class NotifyForm : Form
{
string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\FireWallet\\";
Dictionary<string, string> theme;
public NotifyForm(string Message)
{
InitializeComponent();
labelmessage.Text = Message;
}
#region Theming
private void UpdateTheme()
{
// Check if file exists
if (!Directory.Exists(dir))
{
CreateConfig(dir);
}
if (!File.Exists(dir + "theme.txt"))
{
CreateConfig(dir);
}
// Read file
StreamReader sr = new StreamReader(dir + "theme.txt");
theme = new Dictionary<string, string>();
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
string[] split = line.Split(':');
theme.Add(split[0].Trim(), split[1].Trim());
}
sr.Dispose();
if (!theme.ContainsKey("background") || !theme.ContainsKey("background-alt") || !theme.ContainsKey("foreground") || !theme.ContainsKey("foreground-alt"))
{
return;
}
// Apply theme
this.BackColor = ColorTranslator.FromHtml(theme["background"]);
// Foreground
this.ForeColor = ColorTranslator.FromHtml(theme["foreground"]);
// Need to specify this for each groupbox to override the black text
foreach (Control c in Controls)
{
ThemeControl(c);
}
// Transparancy
applyTransparency(theme);
}
private void ThemeControl(Control c)
{
if (c.GetType() == typeof(GroupBox) || c.GetType() == typeof(Panel))
{
c.ForeColor = ColorTranslator.FromHtml(theme["foreground"]);
foreach (Control sub in c.Controls)
{
ThemeControl(sub);
}
}
if (c.GetType() == typeof(TextBox) || c.GetType() == typeof(Button)
|| c.GetType() == typeof(ComboBox) || c.GetType() == typeof(StatusStrip))
{
c.ForeColor = ColorTranslator.FromHtml(theme["foreground-alt"]);
c.BackColor = ColorTranslator.FromHtml(theme["background-alt"]);
}
}
private void applyTransparency(Dictionary<string, string> theme)
{
if (theme.ContainsKey("transparent-mode"))
{
switch (theme["transparent-mode"])
{
case "mica":
var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };
var accentStructSize = Marshal.SizeOf(accent);
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData
{
Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,
SizeOfData = accentStructSize,
Data = accentPtr
};
User32.SetWindowCompositionAttribute(Handle, ref data);
Marshal.FreeHGlobal(accentPtr);
break;
case "key":
if (theme.ContainsKey("transparency-key"))
{
switch (theme["transparency-key"])
{
case "alt":
this.TransparencyKey = ColorTranslator.FromHtml(theme["background-alt"]);
break;
case "main":
this.TransparencyKey = ColorTranslator.FromHtml(theme["background"]);
break;
default:
this.TransparencyKey = ColorTranslator.FromHtml(theme["transparency-key"]);
break;
}
}
break;
case "percent":
if (theme.ContainsKey("transparency-percent"))
{
Opacity = Convert.ToDouble(theme["transparency-percent"]) / 100;
}
break;
}
}
}
private void CreateConfig(string dir)
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
StreamWriter sw = new StreamWriter(dir + "theme.txt");
sw.WriteLine("background: #000000");
sw.WriteLine("foreground: #8e05c2");
sw.WriteLine("background-alt: #3e065f");
sw.WriteLine("foreground-alt: #ffffff");
sw.WriteLine("transparent-mode: off");
sw.WriteLine("transparency-key: main");
sw.WriteLine("transparency-percent: 90");
sw.Dispose();
}
// Required for mica effect
internal enum AccentState
{
ACCENT_DISABLED = 0,
ACCENT_ENABLE_GRADIENT = 1,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_INVALID_STATE = 4
}
internal enum WindowCompositionAttribute
{
WCA_ACCENT_POLICY = 19
}
[StructLayout(LayoutKind.Sequential)]
internal struct AccentPolicy
{
public AccentState AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct WindowCompositionAttributeData
{
public WindowCompositionAttribute Attribute;
public IntPtr Data;
public int SizeOfData;
}
internal static class User32
{
[DllImport("user32.dll")]
internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);
}
#endregion
private void NotifyForm_Load(object sender, EventArgs e)
{
UpdateTheme();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

120
FireWallet/NotifyForm.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>