Skip to content

Commit

Permalink
v2 Overhaul
Browse files Browse the repository at this point in the history
- Switch to RestSharp for base connectivity
- Complete overhaul of JSON objects to be more consistently named
- Remove interspersed logic between models and backing JSON objects
- Better logic for converging network topology
- Add hotspot management support
- Add miscellaneous statistical information
- Configure network device flags
- Method/class visibility adjustments to make usage more obvious
- Massive in-code documentation improvements
  • Loading branch information
anthturner committed Mar 18, 2018
1 parent 97edf63 commit f26e161
Show file tree
Hide file tree
Showing 70 changed files with 3,352 additions and 2,545 deletions.
576 changes: 288 additions & 288 deletions .gitignore

Large diffs are not rendered by default.

42 changes: 21 additions & 21 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
MIT License

Copyright (c) 2017 Anthony Turner

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
MIT License
Copyright (c) 2017 Anthony Turner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
133 changes: 70 additions & 63 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,63 +1,70 @@
# UniFiSharp

_Bringing Ubiquiti UniFi Orchestration Automation to C#_

UniFiSharp provides a basic C# API for Ubiquiti UniFi controllers, as well as an orchestration overlay to more easily visualize network topology and execute device commands. UniFiSharp also implements both v1 and v2 of the Ubiquiti discovery protocol for automated controller discovery.

This project is anchored in a .NET Core implementation, targeting a minimum of NETCoreApp1.1 and NET4.6.1. All future contributions are planned to continue to enable cross-platform usage via .NET Core.

### Basic API Usage
The `UniFiApi` class provides all base-level API features:

```csharp
# Instantiate the API object
var api = new UniFiSharp.UniFiApi(new Uri("https://controller:8443/"), "username", "password", "siteName");

# Manually calling .Authenticate() is optional -- it will be automatically called if the wrapper is not authenticated when executing a command
await api.Authenticate();

# ... for example, enumerate all UniFi devices known by the controller:
List<UniFiSharp.Protocol.NetworkDevice> uniFiDevices = await api.ListDevices();

# ... or upgrade the firmware on a device:
await api.Upgrade("01:23:45:67:89:AB");
```

### UBNT Cloud
The `UniFiApi` class can also be used with UBNT Cloud-hosted services by changing the base URI to match the UBNT Cloud format:

```csharp
# Instantiate the API object
var api = new UniFiApi(new Uri("https://demo.ubnt.com/manage"), "username", "password");

# Manually calling .Authenticate() is optional -- it will be automatically called if the wrapper is not authenticated when executing a command
await api.Authenticate();

# The below command will retrieve all devices from the UBNT cloud's demo site
List<UniFiSharp.Protocol.NetworkDevice> uniFiDevices = await api.ListDevices();
```

*Note: The above code works as-written; at the time of this writing, Ubiquiti's cloud will accept the above demo credentials and allow the user to work in a sandboxed, artificial environment. This demo setup includes approximately 130 UniFi devices and 1200 clients.*

### Orchestration Usage
In order to make this system more developer-friendly, it also ships with an orchestration overlay that wraps the `UniFiApi` object and associates common information to their devices, as well as attempting to converge a basic topology based on the device objects:

```csharp
# Instantiate the API object the same way as with basic usage
var api = new UniFiSharp.UniFiApi(new Uri("https://controller:8443/"), "username", "password", "siteName");

# Create a NetworkDeploymentSite object that wraps the API instance -- this is the base object for site orchestration
var site = new UniFiSharp.Orchestration.NetworkDeploymentSite(api);

# Refresh all parameters in the site -- this includes WLANs, Port Forwards, User/WLAN Groups, etc.
await site.Refresh();

# ... for example, create a wireless network with a given User Group and WLAN Group:
await site.WirelessNetworks.Add("SSID1", "WlanKey", site.UserGroups.First(), site.WirelessNetworkGroups.First());

# ... or add a port forward to 192.168.1.100/TCP(80), if you're using a UniFi Security Gateway:
await site.PortForwards.Add("Port Forward Example", "tcp", "any", "192.168.1.100", 80, 80);
```

### Disclaimer
This software is not affiliated with nor supported by Ubiquiti Networks and is offered under the license as described in `LICENSE`. This software should *never* be used in a production environment without exhaustive, independent testing.
# UniFiSharp

_Bringing Ubiquiti UniFi Orchestration Automation to C#_

UniFiSharp provides a basic C# API for Ubiquiti UniFi controllers, as well as an orchestration overlay to more easily visualize network topology and execute device commands. UniFiSharp also implements both v1 and v2 of the Ubiquiti discovery protocol for automated controller discovery.

**As of UniFiSharp v1.1.0, the API surface has changed slightly to improve usability and maintainability; please read the usage documentation below.**

This project is written for any .NET application that can consume a .NET Standard 2.0 library. All future contributions are planned to continue to enable cross-platform use.

### Basic API Usage
The `UniFiApi` class provides all base-level API features:

```csharp
// Instantiate the API object
using (var api = new UniFiSharp.UniFiApi(new Uri("https://controller:8443"), "username", "password", "siteName"))
{
// Manually calling .Authenticate() forces the API to proactively authenticate.
// Otherwise, the request will be automatically authenticated upon receiving an unauthorized error.
await api.Authenticate();

// ... for example, enumerate all UniFi devices known by the controller:
IEnumerable<UniFiSharp.Json.JsonNetworkDevice> uniFiDevices = await api.NetworkDeviceList();

// ... or to upgrade the firmware on a device:
await api.NetworkDeviceUpgrade("01:23:45:67:89:AB");
}
```

### UBNT Cloud
The `UniFiApi` class can also be used with UBNT Cloud-hosted services by changing the base URI to match the UBNT Cloud format:

```csharp
var api = new UniFiSharp.UniFiApi(new Uri("https://demo.ubnt.com/"), "username", "password")
```

*Note: At the time of this writing, Ubiquiti's cloud will accept the above demo credentials and allow the user to work in a sandboxed, artificial environment. This demo setup includes approximately 130 UniFi devices and 1200 clients.*

### Orchestration Usage
In order to make this system more developer-friendly, it also ships with an orchestration overlay that wraps the `UniFiApi` object and associates common information to their devices, as well as attempting to converge a basic topology based on the device objects:

```csharp
// Instantiate the API object
using (var api = new UniFiSharp.UniFiApi(new Uri("https://controller:8443"), "username", "password", "siteName"))
using (var orchestrator = new UniFiSharp.Orchestration.UniFiOrchestrator(api))
{
// Calls api.Refresh() under the hood
await orchestrator.Refresh();

// ... for example, retrieve the first AP and turn on its locator for 5 seconds:
await orchestrator.InfrastructureDevices.First(d => d is UniFiSharp.Orchestration.Devices.AccessPointInfrastructureNetworkedDevice).Locate(5000);

// ... or to browse the network topology from the edge inwards, start from:
INetworkedDevice networkRoot = orchestrator.TopologicalRoot;

// ... or to create a new port forward (to 192.168.1.100:TCP/80):
await orchestrator.PortForwards.Add(
UniFiSharp.Orchestration.Models.PortForward.Create(
name: "abc",
proto: "tcp",
source: "any",
sourcePort: 80,
dest: "192.168.1.100",
destPort: 80
));
}
```

### Disclaimer
This software is not affiliated with nor supported by Ubiquiti Networks and is offered under the license as described in `LICENSE`. This software should *never* be used in a production environment without exhaustive, independent testing.
62 changes: 31 additions & 31 deletions UniFiSharp.sln
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniFiSharp", "UniFiSharp\UniFiSharp.csproj", "{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3B4270B0-A3C6-426E-B7B2-7C0C5F9325DA}"
ProjectSection(SolutionItems) = preProject
LICENSE = LICENSE
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7CB25D5C-B0E6-4079-B07D-C29D5B391CF0}
EndGlobalSection
EndGlobal

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2024
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniFiSharp", "UniFiSharp\UniFiSharp.csproj", "{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3B4270B0-A3C6-426E-B7B2-7C0C5F9325DA}"
ProjectSection(SolutionItems) = preProject
LICENSE = LICENSE
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3D81DE3B-4058-41A2-B5C5-A58ADF85668D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7CB25D5C-B0E6-4079-B07D-C29D5B391CF0}
EndGlobalSection
EndGlobal
145 changes: 145 additions & 0 deletions UniFiSharp/DefaultUniFiRestClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
using GcmSharp.Serialization;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UniFiSharp.Json;

namespace UniFiSharp
{
internal class DefaultUniFiRestClient : RestClient, IUniFiRestClient
{
private string _username, _password;

internal DefaultUniFiRestClient(Uri baseUrl, string username, string password) : base(baseUrl)
{
_username = username;
_password = password;

CookieContainer = new System.Net.CookieContainer();

AddHandler("application/json", NewtonsoftJsonSerializer.Default);
AddHandler("text/json", NewtonsoftJsonSerializer.Default);
AddHandler("text/x-json", NewtonsoftJsonSerializer.Default);
AddHandler("text/javascript", NewtonsoftJsonSerializer.Default);
AddHandler("*+json", NewtonsoftJsonSerializer.Default);
}

public async Task UniFiGet(string url)
{
await UniFiRequest(Method.GET, url);
}

public async Task<T> UniFiGet<T>(string url) where T : new()
{
return await UniFiRequest<T>(Method.GET, url);
}

public async Task<IList<T>> UniFiGetMany<T>(string url) where T : new()
{
return await UniFiRequestMany<T>(Method.GET, url);
}

public async Task UniFiPost(string url, object jsonBody)
{
await UniFiRequest(Method.POST, url, jsonBody);
}

public async Task<T> UniFiPost<T>(string url, object jsonBody) where T : new()
{
return await UniFiRequest<T>(Method.POST, url, jsonBody);
}

public async Task<IList<T>> UniFiPostMany<T>(string url, object jsonBody) where T : new()
{
return await UniFiRequestMany<T>(Method.POST, url, jsonBody);
}

public async Task UniFiPut(string url, object jsonBody)
{
await UniFiRequest(Method.PUT, url, jsonBody);
}

public async Task<T> UniFiPut<T>(string url, object jsonBody) where T : new()
{
return await UniFiRequest<T>(Method.PUT, url, jsonBody);
}

public async Task<IList<T>> UniFiPutMany<T>(string url, object jsonBody) where T : new()
{
return await UniFiRequestMany<T>(Method.PUT, url, jsonBody);
}

public async Task UniFiDelete(string url)
{
await UniFiRequest(Method.DELETE, url);
}

private async Task UniFiRequest(Method method, string url, object jsonBody = null)
{
var request = new RestRequest(url, method);
if ((method == Method.POST || method == Method.PUT) && jsonBody != null)
request.AddJsonBody(jsonBody);
await ExecuteRequest<object>(request);
}

private async Task<T> UniFiRequest<T>(Method method, string url, object jsonBody = null) where T : new()
{
var request = new RestRequest(url, method);
if ((method == Method.POST || method == Method.PUT) && jsonBody != null)
request.AddJsonBody(jsonBody);
var envelope = await ExecuteRequest<T>(request);
return (envelope.Data == null) ? default(T) : envelope.Data[0];
}

private async Task<IList<T>> UniFiRequestMany<T>(Method method, string url, object jsonBody = null) where T : new()
{
var request = new RestRequest(url, method);
if ((method == Method.POST || method == Method.PUT) && jsonBody != null)
request.AddJsonBody(jsonBody);
var envelope = await ExecuteRequest<T>(request);
return (envelope.Data == null) ? new List<T>() : new List<T>(envelope.Data);
}

public async Task Authenticate()
{
await UniFiPost("api/login", new
{
username = _username,
password = _password,
remember = false,
strict = true
});
}

private async Task<JsonMessageEnvelope<T>> ExecuteRequest<T>(IRestRequest request, bool attemptReauthentication = true) where T : new()
{
this.AddDefaultHeader("Referrer", BaseUrl.ToString());

if (this.CookieContainer.GetCookies(this.BaseUrl).Count > 0)
{
try { this.AddDefaultHeader("X-Csrf-Token", this.CookieContainer.GetCookies(this.BaseUrl)["csrf_token"].Value); }
catch { }
}

request.RequestFormat = DataFormat.Json;
request.JsonSerializer = NewtonsoftJsonSerializer.Default;

var response = await ExecuteTaskAsync<JsonMessageEnvelope<T>>(request);
var envelope = response.Data;

if (envelope == null && !response.IsSuccessful)
throw response.ErrorException;

if (!envelope.IsSuccessfulResponse &&
envelope.Metadata.Message == "api.err.LoginRequired" &&
attemptReauthentication)
{
await Authenticate();
return await ExecuteRequest<T>(request, false);
}

return response.Data;
}
}
}
Loading

0 comments on commit f26e161

Please sign in to comment.