techgarage-ir.MTWireGuard/MikrotikAPI/APIWrapper.cs

414 lines
14 KiB
C#
Raw Normal View History

2023-06-02 15:26:29 +03:30
using MikrotikAPI.Models;
2023-03-03 23:24:18 +03:30
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text;
2023-06-02 15:26:29 +03:30
namespace MikrotikAPI
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
public class APIWrapper
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
private string MT_IP { get; set; }
private string MT_USER { get; set; }
private string MT_PASS { get; set; }
2023-03-03 23:24:18 +03:30
2023-06-02 15:26:29 +03:30
public APIWrapper(string IP, string User, string Password)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
MT_IP = IP;
MT_USER = User;
MT_PASS = Password;
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<List<Log>> GetLogsAsync()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
string json = await SendGetRequestAsync(Endpoints.Log);
return json.ToModel<List<Log>>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<List<WGServer>> GetServersAsync()
{
string json = await SendGetRequestAsync(Endpoints.Wireguard);
return json.ToModel<List<WGServer>>();
}
public async Task<WGServer> GetServer(string Name)
2023-03-03 23:24:18 +03:30
{
var servers = await GetServersAsync();
return servers.Find(s => s.Name == Name);
}
2023-06-02 15:26:29 +03:30
public async Task<List<ServerTraffic>> GetServersTraffic()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendRequestBase(RequestMethod.GET, Endpoints.Interface, "{\"stats\", {\".proplist\":\"name, type, rx-byte, tx-byte\"}}");
return json.ToModel<List<ServerTraffic>>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<List<WGPeer>> GetUsersAsync()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
string json = await SendGetRequestAsync(Endpoints.WireguardPeers);
return json.ToModel<List<WGPeer>>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<WGPeer> GetUser(string id)
2023-03-03 23:24:18 +03:30
{
var users = await GetUsersAsync();
return users.Find(u => u.Id == id);
}
2023-06-02 15:26:29 +03:30
public async Task<MTInfo> GetInfo()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendGetRequestAsync(Endpoints.SystemResource);
return json.ToModel<MTInfo>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<MTIdentity> GetName()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendGetRequestAsync(Endpoints.SystemIdentity);
return json.ToModel<MTIdentity>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<LoginStatus> TryConnectAsync()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var connection = await SendGetRequestAsync(Endpoints.Empty, true);
return connection.ToModel<LoginStatus>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<List<ActiveUser>> GetActiveSessions()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendGetRequestAsync($"{Endpoints.ActiveUsers}?name=" + MT_USER);
return json.ToModel<List<ActiveUser>>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<List<Job>> GetJobs()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendGetRequestAsync(Endpoints.Jobs);
return json.ToModel<List<Job>>();
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<string> KillJob(string JobID)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
return await SendDeleteRequestAsync($"{Endpoints.Jobs}/" + JobID);
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> CreateServer(WGServerCreateModel server)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendPutRequestAsync(Endpoints.Wireguard, server);
2023-03-03 23:24:18 +03:30
var obj = JObject.Parse(json);
bool success = false;
string code = string.Empty, message = string.Empty, detail = string.Empty;
if (obj.TryGetValue(".id", out var Id))
{
success = true;
}
else if (obj.TryGetValue("error", out var Error))
{
var error = JsonConvert.DeserializeObject<CreationStatus>(json);
success = false;
code = Error.Value<string>();
message = error.Message;
detail = error.Detail;
}
else
{
success = false;
message = "Failed";
detail = json;
};
return new()
{
Code = code,
Message = message,
Detail = detail,
Success = success
};
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> CreateUser(WGPeerCreateModel user)
2023-03-03 23:24:18 +03:30
{
var jsonData = JObject.Parse(JsonConvert.SerializeObject(user, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
}));
2023-06-02 15:26:29 +03:30
var json = await SendPutRequestAsync(Endpoints.WireguardPeers, jsonData);
2023-03-03 23:24:18 +03:30
var obj = JObject.Parse(json);
bool success = false;
string code = string.Empty, message = string.Empty, detail = string.Empty;
WGPeer peer = null;
if (obj.TryGetValue(".id", out var Id))
{
success = true;
peer = JsonConvert.DeserializeObject<WGPeer>(json);
}
else if (obj.TryGetValue("error", out var Error))
{
var error = JsonConvert.DeserializeObject<CreationStatus>(json);
success = false;
code = Error.Value<string>();
message = error.Message;
detail = error.Detail;
}
else
{
success = false;
message = "Failed";
detail = json;
};
return new()
{
Code = code,
Message = message,
Detail = detail,
Success = success,
Item = peer ?? null
};
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> UpdateServer(WGServerUpdateModel server)
2023-03-03 23:24:18 +03:30
{
var serverJson = JObject.Parse(JsonConvert.SerializeObject(server, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
}));
2023-06-02 15:26:29 +03:30
var json = await SendPatchRequestAsync($"{Endpoints.Wireguard}/{server.Id}", serverJson);
2023-03-03 23:24:18 +03:30
var obj = JObject.Parse(json);
bool success = false;
string code = string.Empty, message = string.Empty, detail = string.Empty;
WGServer srv = null;
if (obj.TryGetValue(".id", out var Id))
{
success = true;
srv = JsonConvert.DeserializeObject<WGServer>(json);
}
else if (obj.TryGetValue("error", out var Error))
{
var error = JsonConvert.DeserializeObject<CreationStatus>(json);
success = false;
code = Error.Value<string>();
message = error.Message;
detail = error.Detail;
}
else
{
success = false;
message = "Failed";
detail = json;
};
return new()
{
Code = code,
Message = message,
Detail = detail,
Success = success,
Item = srv ?? null
};
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> UpdateUser(WGPeerUpdateModel user)
2023-03-03 23:24:18 +03:30
{
var userJson = JObject.Parse(JsonConvert.SerializeObject(user, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
}));
2023-06-02 15:26:29 +03:30
var json = await SendPatchRequestAsync($"{Endpoints.WireguardPeers}/{user.Id}", userJson);
2023-03-03 23:24:18 +03:30
var obj = JObject.Parse(json);
bool success = false;
string code = string.Empty, message = string.Empty, detail = string.Empty;
WGPeer peer = null;
if (obj.TryGetValue(".id", out var Id))
{
success = true;
peer = JsonConvert.DeserializeObject<WGPeer>(json);
}
else if (obj.TryGetValue("error", out var Error))
{
var error = JsonConvert.DeserializeObject<CreationStatus>(json);
success = false;
code = Error.Value<string>();
message = error.Message;
detail = error.Detail;
}
else
{
success = false;
message = "Failed";
detail = json;
};
return new()
{
Code = code,
Message = message,
Detail = detail,
Success = success,
Item = peer ?? null
};
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> SetServerEnabled(WGEnability enability)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendPatchRequestAsync($"{Endpoints.Wireguard}/{enability.ID}", new { disabled = enability.Disabled });
2023-03-03 23:24:18 +03:30
var obj = JObject.Parse(json);
bool success = false;
string code = string.Empty, message = string.Empty, detail = string.Empty;
WGPeer peer = null;
if (obj.TryGetValue(".id", out var Id))
{
success = true;
peer = JsonConvert.DeserializeObject<WGPeer>(json);
}
else if (obj.TryGetValue("error", out var Error))
{
var error = JsonConvert.DeserializeObject<CreationStatus>(json);
success = false;
code = Error.Value<string>();
message = error.Message;
detail = error.Detail;
}
else
{
success = false;
message = "Failed";
detail = json;
};
return new()
{
Code = code,
Message = message,
Detail = detail,
Success = success,
Item = peer ?? null
};
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> SetUserEnabled(WGEnability enability)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendPatchRequestAsync($"{Endpoints.WireguardPeers}/{enability.ID}", new { disabled = enability.Disabled });
2023-03-03 23:24:18 +03:30
var obj = JObject.Parse(json);
bool success = false;
string code = string.Empty, message = string.Empty, detail = string.Empty;
WGPeer peer = null;
if (obj.TryGetValue(".id", out var Id))
{
success = true;
peer = JsonConvert.DeserializeObject<WGPeer>(json);
}
else if (obj.TryGetValue("error", out var Error))
{
var error = JsonConvert.DeserializeObject<CreationStatus>(json);
success = false;
code = Error.Value<string>();
message = error.Message;
detail = error.Detail;
}
else
{
success = false;
message = "Failed";
detail = json;
};
return new()
{
Code = code,
Message = message,
Detail = detail,
Success = success,
Item = peer ?? null
};
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> DeleteServer(string id)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendDeleteRequestAsync($"{Endpoints.Wireguard}/" + id);
2023-03-03 23:24:18 +03:30
if (string.IsNullOrWhiteSpace(json))
{
return new()
{
Success = true
};
}
else
{
return new()
{
Success = false,
Item = json
};
}
}
2023-06-02 15:26:29 +03:30
public async Task<CreationStatus> DeleteUser(string id)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
var json = await SendDeleteRequestAsync($"{Endpoints.WireguardPeers}/" + id);
2023-03-03 23:24:18 +03:30
if (string.IsNullOrWhiteSpace(json))
{
return new()
{
Success = true
};
}
else
{
return new()
{
Success = false,
Item = json
};
}
}
2023-06-02 15:26:29 +03:30
public async Task<string> GetTrafficSpeed()
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
return await SendPostRequestAsync(Endpoints.MonitorTraffic, "{\"interface\":\"ether1\",\"duration\":\"3s\"}");
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
private async Task<string> SendRequestBase(RequestMethod Method, string Endpoint, object Data = null, bool IsTest = false)
2023-03-03 23:24:18 +03:30
{
HttpClientHandler handler = new()
{
2023-06-02 15:26:29 +03:30
ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true
2023-03-03 23:24:18 +03:30
};
using HttpClient httpClient = new(handler);
2023-06-02 15:26:29 +03:30
using var request = new HttpRequestMessage(new HttpMethod(Method.ToString()), $"https://{MT_IP}/rest/{Endpoint}");
2023-03-03 23:24:18 +03:30
string base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{MT_USER}:{MT_PASS}"));
if (!IsTest) request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
2023-06-02 15:26:29 +03:30
if (Data != null)
{
string content = (Data is string @string) ? @string : JsonConvert.SerializeObject(Data);
request.Content = new StringContent(content);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
}
2023-03-03 23:24:18 +03:30
HttpResponseMessage response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
2023-06-02 15:26:29 +03:30
private async Task<string> SendGetRequestAsync(string URL, bool IsTest = false)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
return await SendRequestBase(RequestMethod.GET, URL, IsTest: IsTest);
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
private async Task<string> SendPostRequestAsync(string URL, string Data)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
return await SendRequestBase(RequestMethod.POST, URL, Data);
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
private async Task<string> SendDeleteRequestAsync(string URL)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
return await SendRequestBase(RequestMethod.DELETE, URL);
2023-03-03 23:24:18 +03:30
}
2023-06-02 15:26:29 +03:30
private async Task<string> SendPutRequestAsync(string URL, object Data)
2023-03-03 23:24:18 +03:30
{
2023-06-02 15:26:29 +03:30
return await SendRequestBase(RequestMethod.PUT, URL, Data);
}
2023-03-03 23:24:18 +03:30
2023-06-02 15:26:29 +03:30
private async Task<string> SendPatchRequestAsync(string URL, object Data)
{
return await SendRequestBase(RequestMethod.PATCH, URL, Data);
2023-03-03 23:24:18 +03:30
}
}
}