lucidiot/HabitSharp
lucidiot
/
HabitSharp
Archived
1
0
Fork 0
This repository has been archived on 2022-08-04. You can view files and clone it, but cannot push or open issues or pull requests.
HabitSharp/HabitSharp/HabiticaApi.cs

61 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using RestSharp;
using HabitSharp.Managers;
using HabitSharp.Serialization;
namespace HabitSharp
{
public class HabiticaApi
{
const string BaseURL = "https://habitica.com/api/v3";
private readonly RestClient Client;
public readonly TagManager Tags;
public readonly NotificationManager Notifications;
public HabiticaApi(string UserID, string ApiKey) : this(Guid.Parse(UserID), Guid.Parse(ApiKey)) { }
public HabiticaApi(Guid UserID, Guid ApiKey)
{
this.Client = new RestClient(BaseURL);
this.Client.Authenticator = new HabiticaAuthenticator(UserID, ApiKey);
// Override JSON serialization
this.Client.AddHandler(
() => NewtonsoftJsonSerializer.Default,
"application/json",
"text/json",
"text/x-json",
"text/javascript",
"*+json"
);
this.Tags = new TagManager(this);
this.Notifications = new NotificationManager(this);
}
public T Execute<T>(RestRequest request) where T : new() {
var response = Client.Execute<T>(request);
if (response.ErrorException != null) throw new ApplicationException(
"An error occured while running a Habitica API request. See inner exception for more info",
response.ErrorException);
// TODO: Raise exception on error, error message, param errors or !Success
return response.Data;
}
public Result<Dictionary<string, string>> GetModelPaths(string ModelName) {
var req = new RestRequest("models/{model}/paths");
req.AddUrlSegment("model", ModelName);
return this.Execute<Result<Dictionary<string, string>>>(req);
}
public bool CheckStatus() {
var result = this.Execute<Result<Dictionary<string, string>>>(new RestRequest("status"));
return result.Success && result.Data.ContainsKey("status") && result.Data["status"] == "up";
}
}
}