Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ public class ProjectsOptions : Options
{
}

[Verb("recent", HelpText = "Shows details of recent timers.")]
public class RecentOptions : Options
{
}

[Verb("current", HelpText = "Shows details of the current timer.")]
public class CurrentOptions : Options
{
Expand Down Expand Up @@ -64,8 +69,9 @@ static void Main(string[] args)
Console.OutputEncoding = Encoding.UTF8;
try
{
Parser.Default.ParseArguments<ProjectsOptions, CurrentOptions, SetOptions, StartOptions, StopOptions>(args)
Parser.Default.ParseArguments<ProjectsOptions, RecentOptions, CurrentOptions, SetOptions, StartOptions, StopOptions>(args)
.WithParsed<ProjectsOptions>(options => Projects(options).Wait())
.WithParsed<RecentOptions>(options => Recent(options).Wait())
.WithParsed<CurrentOptions>(options => Current(options).Wait())
.WithParsed<SetOptions>(options => Set(options).Wait())
.WithParsed<StartOptions>(options => Start(options).Wait())
Expand Down Expand Up @@ -100,6 +106,17 @@ static async Task<Project> GetMatchingProject(Query query, string projectNameOrI
return project;
}

static async Task<string> FormatTimer(Query query, TimeEntry timer)
{
var project = await query.GetProject(timer.pid);
if (timer.stop.Year == 1)
{
var duration = TimeSpan.FromSeconds(DateTimeOffset.Now.ToUnixTimeSeconds() + timer.duration);
return $"{timer.start.ToString("yyyy-MM-dd HH:mm")}-now ({duration.ToString("hh\\:mm")}) - {project.name} - {timer.description} [{(timer.tags == null ? "" : string.Join(", ", timer.tags))}]";
}
return $"{timer.start.ToString("yyyy-MM-dd HH:mm")}-{timer.stop.TimeOfDay.ToString("hh\\:mm")} ({(timer.stop - timer.start).ToString("hh\\:mm")}) - {project.name} - {timer.description} [{(timer.tags == null ? "" : string.Join(", ", timer.tags))}]";
}

static async Task Projects(ProjectsOptions options)
{
var query = GetQuery(options);
Expand All @@ -113,6 +130,15 @@ static async Task Projects(ProjectsOptions options)
}
}

static async Task Recent(Options options)
{
var query = GetQuery(options);
foreach (var timer in await query.GetRecentTimers())
{
Console.WriteLine(await FormatTimer(query, timer));
}
}

static async Task Current(Options options)
{
var query = GetQuery(options);
Expand All @@ -123,9 +149,7 @@ static async Task Current(Options options)
}
else
{
var project = await query.GetProject(timer.pid);
var duration = TimeSpan.FromSeconds(DateTimeOffset.Now.ToUnixTimeSeconds() + timer.duration);
Console.WriteLine($"\u25B6\uFE0F {duration} - {project.name} - {timer.description} [{(timer.tags == null ? "" : string.Join(", ", timer.tags))}]");
Console.WriteLine($"\u25B6\uFE0F {await FormatTimer(query, timer)}");
}
}

Expand Down
56 changes: 41 additions & 15 deletions Toggl/Query.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Expand All @@ -25,6 +27,7 @@ public TogglException(string message, Exception inner) : base(message, inner)
readonly string Token;

HttpClient Client = new HttpClient();
Dictionary<int, Project> ProjectCache = new Dictionary<int, Project>();

public Query(string token)
{
Expand All @@ -35,21 +38,30 @@ internal async Task<JToken> Send(HttpMethod method, string type, HttpContent con
{
var uri = new Uri(Endpoint + type);

var request = new HttpRequestMessage(method, uri);
request.Headers.UserAgent.Clear();
request.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse(UserAgent));
request.Headers.Authorization = new AuthenticationHeaderValue("basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Token}:api_token")));
request.Content = content;

var response = await Client.SendAsync(request);
var text = await response.Content.ReadAsStringAsync();
try
{
return JToken.Parse(text);
}
catch (JsonReaderException error)
while (true)
{
throw new TogglException(text, error);
var request = new HttpRequestMessage(method, uri);
request.Headers.UserAgent.Clear();
request.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse(UserAgent));
request.Headers.Authorization = new AuthenticationHeaderValue("basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Token}:api_token")));
request.Content = content;

var response = await Client.SendAsync(request);
if (response.StatusCode == HttpStatusCode.TooManyRequests)
{
Thread.Sleep(1000);
continue;
}

var text = await response.Content.ReadAsStringAsync();
try
{
return JToken.Parse(text);
}
catch (JsonReaderException error)
{
throw new TogglException(text, error);
}
}
}

Expand All @@ -68,6 +80,15 @@ internal async Task<JToken> Put(string type, JObject content)
return await Send(HttpMethod.Put, type, new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json"));
}

internal async Task<U> GetCached<T, U>(Dictionary<T, U> cache, T key, Func<Task<U>> generator)
{
if (!cache.ContainsKey(key))
{
cache[key] = await generator();
}
return cache[key];
}

public async Task<IReadOnlyList<Workspace>> GetWorkspaces()
{
return (await Get("workspaces")).ToObject<List<Workspace>>();
Expand All @@ -88,7 +109,12 @@ public async Task<IReadOnlyList<Project>> GetProjects(Workspace workspace)

public async Task<Project> GetProject(int projectId)
{
return (await Get($"projects/{projectId}"))["data"].ToObject<Project>();
return await GetCached(ProjectCache, projectId, async () => (await Get($"projects/{projectId}"))["data"].ToObject<Project>());
}

public async Task<IReadOnlyList<TimeEntry>> GetRecentTimers()
{
return (await Get("time_entries")).ToObject<IReadOnlyList<TimeEntry>>();
}

public async Task<TimeEntry> GetCurrentTimer()
Expand Down