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