Skip to content

Commit 0f84275

Browse files
committed
Cleaned some code and added some command line options
Added command line options: shutdown, restart, upgrade
1 parent 29f0df2 commit 0f84275

File tree

9 files changed

+575
-101
lines changed

9 files changed

+575
-101
lines changed

API.cs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Net.Http;
5+
using System.Net.Http.Headers;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
9+
namespace SyncThingTray
10+
{
11+
static class API
12+
{
13+
public static async Task<string> CallAPIPost(string Query)
14+
{
15+
if (string.IsNullOrWhiteSpace(Program.APIUrl)) return "Syncthing address unavailable";
16+
try
17+
{
18+
HttpClient client = new HttpClient();
19+
client.BaseAddress = new Uri(Program.APIUrl);
20+
client.DefaultRequestHeaders.Accept.Clear();
21+
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
22+
client.DefaultRequestHeaders.Add("X-API-Key", Program.APIKey);
23+
HttpContent cnt = new ByteArrayContent(new byte[0]);
24+
var res = await client.PostAsync("rest/" + Query, cnt);
25+
return res.IsSuccessStatusCode ? null : "Error: " + res.ToString();
26+
}
27+
catch (HttpRequestException x)
28+
{
29+
var i = x.InnerException;
30+
if (i != null) return "Exception: " + i.Message;
31+
return "Exception: " + x.Message;
32+
}
33+
}
34+
35+
public static string CallAPIPostSync(string Query, int Timeout, string Default)
36+
{
37+
var res = CallAPIPost(Query);
38+
if (res.Wait(Timeout))
39+
return res.Result;
40+
else
41+
return Default;
42+
}
43+
44+
public static bool IsAvailable
45+
{
46+
get
47+
{
48+
var res = CallAPIPost("ping");
49+
if (!res.Wait(1000)) return false;
50+
return res.Result == null;
51+
}
52+
}
53+
54+
}
55+
}

Program.cs

Lines changed: 91 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using System.Security.Principal;
1111
using System.Diagnostics;
1212
using System.Reflection;
13+
using System.Xml;
1314

1415
namespace SyncThingTray
1516
{
@@ -58,6 +59,54 @@ static void Main(string[] Args)
5859
Application.Run(f);
5960
return;
6061
}
62+
else if (Args[0].ToLower() == "shutdown")
63+
{
64+
if (IsConfigured)
65+
{
66+
string res = ReadConfiguration();
67+
if (res != null)
68+
Application.Run(new frmMessage(res));
69+
else
70+
{
71+
res = API.CallAPIPostSync("shutdown", 2000, "Tineout occured: No response was received from syncthing");
72+
if (res != null)
73+
Application.Run(new frmMessage(res));
74+
}
75+
return;
76+
}
77+
}
78+
else if (Args[0].ToLower() == "restart")
79+
{
80+
if (IsConfigured)
81+
{
82+
string res = ReadConfiguration();
83+
if (res != null)
84+
Application.Run(new frmMessage(res));
85+
else
86+
{
87+
res = API.CallAPIPostSync("restart", 2000, "Tineout occured: No response was received from syncthing");
88+
if (res != null)
89+
Application.Run(new frmMessage(res));
90+
}
91+
return;
92+
}
93+
}
94+
else if (Args[0].ToLower() == "upgrade")
95+
{
96+
if (IsConfigured)
97+
{
98+
string res = ReadConfiguration();
99+
if (res != null)
100+
Application.Run(new frmMessage(res));
101+
else
102+
{
103+
res = API.CallAPIPostSync("upgrade", 2000, "Tineout occured: No response was received from syncthing");
104+
if (res != null)
105+
Application.Run(new frmMessage(res));
106+
}
107+
return;
108+
}
109+
}
61110
}
62111
if (Environment.UserInteractive)
63112
Application.Run(new frmMain());
@@ -82,10 +131,10 @@ public static bool GetIsRunning(ServiceController Controller)
82131

83132
public static void InstallService()
84133
{
85-
InstallService(ServiceStartMode.Automatic,false, ServiceAccount.LocalSystem, null, null);
134+
InstallService(ServiceStartMode.Automatic, false, ServiceAccount.LocalSystem, null, null);
86135
}
87136

88-
public static void InstallService(ServiceStartMode StartMode,bool DelayedStart, ServiceAccount Account, string UserName, string Password)
137+
public static void InstallService(ServiceStartMode StartMode, bool DelayedStart, ServiceAccount Account, string UserName, string Password)
89138
{
90139
if (IsInstalled) return;
91140
try
@@ -213,7 +262,7 @@ public static bool IsConfigured
213262
MonitorFile = Path.Combine(MonitorFile, "Syncthing Service");
214263
if (!Directory.Exists(MonitorFile)) Directory.CreateDirectory(MonitorFile);
215264
MonitorFile = Path.Combine(MonitorFile, "Std.out");
216-
265+
217266
// Check the configuration
218267
RegistryKey klm = Registry.LocalMachine;
219268
if (klm == null) return false;
@@ -241,5 +290,44 @@ public static bool IsConfigured
241290
}
242291
}
243292
}
293+
294+
public static string GuiUrl { get; private set; }
295+
public static string APIUrl { get; private set; }
296+
public static string APIKey { get; private set; }
297+
298+
public static string ReadConfiguration()
299+
{
300+
string cfgpath = Path.Combine(Program.SyncConfigPath, "config.xml");
301+
if (File.Exists(cfgpath))
302+
{
303+
XmlDocument xml = new XmlDocument();
304+
xml.Load(cfgpath);
305+
XmlElement xr = xml.DocumentElement;
306+
var xgs = xr.GetElementsByTagName("gui");
307+
if (xgs.Count == 1)
308+
{
309+
XmlElement xg = (XmlElement)xgs[0];
310+
string tls = xg.GetAttribute("tls");
311+
var xas = xg.GetElementsByTagName("address");
312+
if (xas.Count == 1)
313+
{
314+
GuiUrl = (tls == "true" ? "https://" : "http://") + xas[0].InnerText;
315+
APIUrl = "http://" + xas[0].InnerText;
316+
}
317+
else
318+
return "The http address of Syncthing could not be found in the configuration";
319+
xas = xg.GetElementsByTagName("apikey");
320+
if (xas.Count == 1)
321+
APIKey = xas[0].InnerText;
322+
else
323+
return "Could not find the API Key in the configuration: Ensure that an API key was generated in the syncthing GUI";
324+
return null;
325+
}
326+
else
327+
return "The Syncthing configuration cannot be retreived as the gui element could not be found";
328+
}
329+
else
330+
return "The configuration file could not be found: " + cfgpath;
331+
}
244332
}
245333
}

Releases/SyncThingTray.exe

12.5 KB
Binary file not shown.

SyncThingTray.csproj

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
<Reference Include="System.Xml" />
6363
</ItemGroup>
6464
<ItemGroup>
65+
<Compile Include="API.cs" />
6566
<Compile Include="frmInstall.cs">
6667
<SubType>Form</SubType>
6768
</Compile>
@@ -74,6 +75,12 @@
7475
<Compile Include="frmMain.Designer.cs">
7576
<DependentUpon>frmMain.cs</DependentUpon>
7677
</Compile>
78+
<Compile Include="frmMessage.cs">
79+
<SubType>Form</SubType>
80+
</Compile>
81+
<Compile Include="frmMessage.Designer.cs">
82+
<DependentUpon>frmMessage.cs</DependentUpon>
83+
</Compile>
7784
<Compile Include="Program.cs" />
7885
<Compile Include="ProjectInstaller.cs">
7986
<SubType>Component</SubType>
@@ -94,6 +101,9 @@
94101
<EmbeddedResource Include="frmMain.resx">
95102
<DependentUpon>frmMain.cs</DependentUpon>
96103
</EmbeddedResource>
104+
<EmbeddedResource Include="frmMessage.resx">
105+
<DependentUpon>frmMessage.cs</DependentUpon>
106+
</EmbeddedResource>
97107
<EmbeddedResource Include="ProjectInstaller.resx">
98108
<DependentUpon>ProjectInstaller.cs</DependentUpon>
99109
</EmbeddedResource>

SyngThingService.cs

Lines changed: 5 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -131,46 +131,11 @@ static void StopProgram(Process proc)
131131

132132
static string ShutdownProgram()
133133
{
134-
string cfgpath = Path.Combine(Program.SyncConfigPath, "config.xml");
135-
if (File.Exists(cfgpath))
136-
{
137-
string url, key;
138-
XmlDocument xml = new XmlDocument();
139-
xml.Load(cfgpath);
140-
XmlElement xr = xml.DocumentElement;
141-
var xgs = xr.GetElementsByTagName("gui");
142-
if (xgs.Count == 1)
143-
{
144-
XmlElement xg = (XmlElement)xgs[0];
145-
string tls = xg.GetAttribute("tls");
146-
var xas = xg.GetElementsByTagName("address");
147-
if (xas.Count == 1)
148-
url = "http://" + xas[0].InnerText;
149-
else
150-
return "The http address of Syncthing could not be found in the configuration";
151-
xas = xg.GetElementsByTagName("apikey");
152-
if (xas.Count == 1)
153-
key = xas[0].InnerText;
154-
else
155-
return "Could not find the API Key in the configuration: Ensure that an API key was generated in the syncthing GUI";
156-
HttpClient client = new HttpClient();
157-
client.BaseAddress = new Uri(url);
158-
client.DefaultRequestHeaders.Accept.Clear();
159-
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
160-
client.DefaultRequestHeaders.Add("X-API-Key", key);
161-
HttpContent cnt = new ByteArrayContent(new byte[0]);
162-
var res = client.PostAsync("rest/shutdown", cnt);
163-
if (res.Wait(2000))
164-
return res.Result.IsSuccessStatusCode ? null : "Error: " + res.Result.ToString();
165-
else
166-
return null;
167-
}
168-
else
169-
return "The Syncthing configuration cannot be retreived as the gui element could not be found";
170-
}
171-
else
172-
return "The configuration file could not be found: " + cfgpath;
173-
134+
string res= Program.ReadConfiguration();
135+
if (res != null) return res;
136+
var apires = API.CallAPIPost("shutdown");
137+
if (!apires.Wait(2000)) return null;
138+
return apires.Result;
174139
}
175140

176141
}

frmMain.cs

Lines changed: 7 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,6 @@ namespace SyncThingTray
1818
public partial class frmMain : Form
1919
{
2020
bool allowclose = false;
21-
string gui;
22-
string apiurl;
23-
string apikey;
2421
public frmMain()
2522
{
2623
InitializeComponent();
@@ -51,7 +48,7 @@ private void showConsoleToolStripMenuItem_Click(object sender, EventArgs e)
5148

5249
private void showGuiToolStripMenuItem_Click(object sender, EventArgs e)
5350
{
54-
if (!string.IsNullOrWhiteSpace(gui)) Process.Start(gui);
51+
if (!string.IsNullOrWhiteSpace(Program.GuiUrl)) Process.Start(Program.GuiUrl);
5552
}
5653

5754
private void stopServiceToolStripMenuItem_Click(object sender, EventArgs e)
@@ -100,30 +97,9 @@ private void frmMain_VisibleChanged(object sender, EventArgs e)
10097
private void mnuTray_Opening(object sender, CancelEventArgs e)
10198
{
10299
SetServiceStatus(true);
103-
string cfgpath = Path.Combine(Program.SyncConfigPath, "config.xml");
104-
if (File.Exists(cfgpath))
105-
{
106-
XmlDocument xml = new XmlDocument();
107-
xml.Load(cfgpath);
108-
XmlElement xr = xml.DocumentElement;
109-
var xgs = xr.GetElementsByTagName("gui");
110-
if (xgs.Count == 1)
111-
{
112-
XmlElement xg = (XmlElement)xgs[0];
113-
string tls = xg.GetAttribute("tls");
114-
var xas = xg.GetElementsByTagName("address");
115-
if (xas.Count == 1)
116-
{
117-
gui = (tls == "true" ? "https://" : "http://") + xas[0].InnerText;
118-
apiurl = "http://" + xas[0].InnerText;
119-
}
120-
xas = xg.GetElementsByTagName("apikey");
121-
if (xas.Count == 1)
122-
apikey = xas[0].InnerText;
123-
}
124-
}
125-
showGuiToolStripMenuItem.Enabled = !string.IsNullOrWhiteSpace(gui);
126-
if (string.IsNullOrWhiteSpace(apiurl) || string.IsNullOrWhiteSpace(apikey)|| (!Program.IsRunning && !IsAvailable()))
100+
Program.ReadConfiguration();
101+
showGuiToolStripMenuItem.Enabled = !string.IsNullOrWhiteSpace(Program.GuiUrl);
102+
if (string.IsNullOrWhiteSpace(Program.APIUrl) || string.IsNullOrWhiteSpace(Program.APIKey) || (!Program.IsRunning && !API.IsAvailable))
127103
{
128104
mnuRestart.Enabled = false;
129105
mnuShutdown.Enabled = false;
@@ -137,48 +113,21 @@ private void mnuTray_Opening(object sender, CancelEventArgs e)
137113
}
138114
}
139115

140-
bool IsAvailable()
141-
{
142-
var res = CallAPIPost("ping");
143-
if (!res.Wait(1000)) return false;
144-
return res.Result == null;
145-
}
146-
147116
private async void mnuShutdown_Click(object sender, EventArgs e)
148117
{
149-
var res = await CallAPIPost("shutdown");
118+
var res = await API.CallAPIPost("shutdown");
150119
if (res != null) icoTray.ShowBalloonTip(1000, "Syncthing", res, ToolTipIcon.Error);
151120
}
152121

153-
private async Task<string> CallAPIPost(string Query)
154-
{
155-
if (string.IsNullOrWhiteSpace(apiurl)) return "Syncthing address unavailable";
156-
try
157-
{
158-
HttpClient client = new HttpClient();
159-
client.BaseAddress = new Uri(apiurl);
160-
client.DefaultRequestHeaders.Accept.Clear();
161-
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
162-
client.DefaultRequestHeaders.Add("X-API-Key", apikey);
163-
HttpContent cnt = new ByteArrayContent(new byte[0]);
164-
var res = await client.PostAsync("rest/" + Query, cnt);
165-
return res.IsSuccessStatusCode ? null : "Error: " + res.ToString();
166-
}
167-
catch (HttpRequestException x)
168-
{
169-
return "Exception: " + x.Message;
170-
}
171-
}
172-
173122
private async void mnuUpgrade_Click(object sender, EventArgs e)
174123
{
175-
var res = await CallAPIPost("upgrade");
124+
var res = await API.CallAPIPost("upgrade");
176125
if (res != null) icoTray.ShowBalloonTip(1000, "Syncthing", res, ToolTipIcon.Error);
177126
}
178127

179128
private async void mnuRestart_Click(object sender, EventArgs e)
180129
{
181-
var res = await CallAPIPost("restart");
130+
var res = await API.CallAPIPost("restart");
182131
if (res != null) icoTray.ShowBalloonTip(1000, "Syncthing", res, ToolTipIcon.Error);
183132
}
184133

0 commit comments

Comments
 (0)