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(RestRequest request) where T : new() { var response = Client.Execute(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> GetModelPaths(string ModelName) { var req = new RestRequest("models/{model}/paths"); req.AddUrlSegment("model", ModelName); return this.Execute>>(req); } public bool CheckStatus() { var result = this.Execute>>(new RestRequest("status")); return result.Success && result.Data.ContainsKey("status") && result.Data["status"] == "up"; } } }