/
support.go
504 lines (416 loc) · 11.3 KB
/
support.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package main
import (
"fmt"
"log"
"math"
"sort"
"strings"
"time"
"github.com/jason0x43/go-alfred"
"github.com/jason0x43/go-toggl"
"github.com/VojtechVitek/go-trello"
)
func checkRefresh() error {
if config.TestMode {
log.Printf("Test mode is active; not auto-refreshing")
return nil
}
if time.Now().Sub(cache.Time).Minutes() < 5.0 {
return nil
}
log.Println("Refreshing cache...")
err := refresh()
if err != nil {
log.Println("Error refreshing cache:", err)
}
return err
}
func refresh() error {
// toggl
s := toggl.OpenSession(config.ApiKey)
account, err := s.GetAccount()
if err != nil {
return err
}
log.Printf("got account: %#v", account)
cache.Time = time.Now()
cache.Toggl = account
cache.Workspace = account.Data.Workspaces[0].Id
// alfred
ta.GetAccount()
cache.Trello = ta
return alfred.SaveJson(cacheFile, &cache)
}
func getRunningTimer() (toggl.TimeEntry, bool) {
for _, entry := range cache.Toggl.Data.TimeEntries {
if entry.IsRunning() {
return entry, true
}
}
return toggl.TimeEntry{}, false
}
func getProjectsById() map[int]toggl.Project {
projectsById := map[int]toggl.Project{}
for _, proj := range cache.Toggl.Data.Projects {
projectsById[proj.Id] = proj
}
return projectsById
}
func getProjectsByName() map[string]toggl.Project {
projectsByName := map[string]toggl.Project{}
for _, proj := range cache.Toggl.Data.Projects {
projectsByName[proj.Name] = proj
}
return projectsByName
}
func findProjectByName(name string) (toggl.Project, bool) {
for _, proj := range cache.Toggl.Data.Projects {
if proj.Name == name {
return proj, true
}
}
return toggl.Project{}, false
}
func findTimerById(id int) (toggl.TimeEntry, bool) {
for _, entry := range cache.Toggl.Data.TimeEntries[:] {
if entry.Id == id {
return entry, true
}
}
return toggl.TimeEntry{}, false
}
func findTimerByName(name string) (toggl.TimeEntry, bool) {
log.Println(name)
for _, entry := range cache.Toggl.Data.TimeEntries[:] {
log.Println(entry.Description)
if entry.Description == name {
return entry, true
}
}
return toggl.TimeEntry{}, false
}
func findTagByName(name string) (toggl.Tag, bool) {
for _, tag := range cache.Toggl.Data.Tags {
if tag.Name == name {
return tag, true
}
}
return toggl.Tag{}, false
}
func getCardsForQuery(query string) []trello.Card {
entries := cache.Trello.Data.TimeEntries[:]
matchQuery := strings.ToLower(query)
matched := []trello.Card{}
for _, entry := range entries {
if strings.Contains(strings.ToLower(entry.Name), matchQuery) {
matched = append(matched, entry)
}
}
//sort.Sort(sort.Reverse(byTime(matched)))
return matched
}
func getTimeEntriesForQuery(query string) []toggl.TimeEntry {
entries := cache.Toggl.Data.TimeEntries[:]
matchQuery := strings.ToLower(query)
matched := []toggl.TimeEntry{}
for _, entry := range entries {
if strings.Contains(strings.ToLower(entry.Description), matchQuery) {
matched = append(matched, entry)
}
}
sort.Sort(sort.Reverse(byTime(matched)))
return matched
}
func getLatestTimeEntriesForProject(pid int) []toggl.TimeEntry {
entries := cache.Toggl.Data.TimeEntries[:]
matched := map[string]toggl.TimeEntry{}
for _, entry := range entries {
if entry.Pid == pid {
e, ok := matched[entry.Description]
if !ok || (!entry.StartTime().IsZero() && !e.StartTime().IsZero() && entry.StartTime().After(e.StartTime())) {
matched[entry.Description] = entry
}
}
}
matchedArr := []toggl.TimeEntry{}
for _, value := range matched {
matchedArr = append(matchedArr, value)
}
sort.Sort(sort.Reverse(byTime(matchedArr)))
return matchedArr
}
func projectHasTimeEntries(pid int) bool {
entries := cache.Toggl.Data.TimeEntries
for i, _ := range entries {
if entries[i].Pid == pid {
return true
}
}
return false
}
func getLatestTimeEntriesForTag(tag string) []toggl.TimeEntry {
entries := cache.Toggl.Data.TimeEntries[:]
matched := []toggl.TimeEntry{}
for _, entry := range entries {
for _, t := range entry.Tags {
if t == tag {
matched = append(matched, entry)
break
}
}
}
sort.Sort(sort.Reverse(byTime(matched)))
return matched
}
func tagHasTimeEntries(tag string) bool {
entries := cache.Toggl.Data.TimeEntries
for i, _ := range entries {
if entries[i].HasTag(tag) {
return true
}
}
return false
}
func createReportItems(prefix string, parts []string, since, until time.Time) ([]alfred.Item, error) {
var items []alfred.Item
report, err := generateReport(since, until)
if err != nil {
return items, err
}
span := parts[0]
log.Printf("got report with %d projects\n", len(report.projects))
log.Printf("parts: %#v\n", parts)
if len(report.projects) > 0 {
var total int64
var totalName string
var name string
if len(parts) > 1 {
name = parts[1]
}
terminator := strings.Index(name, alfred.Terminator)
if terminator != -1 {
name := name[:terminator]
var project *projectEntry
for _, proj := range report.projects {
if proj.name == name {
project = proj
break
}
}
if project == nil {
return items, fmt.Errorf("Couldn't find project '%s'", name)
}
for _, entry := range project.entries {
item := alfred.Item{
Valid: alfred.Invalid,
Title: entry.description,
SubtitleAll: fmt.Sprintf("%.2f", float32(entry.total)/100.0)}
if entry.running {
item.Icon = "running.png"
}
items = append(items, item)
}
total = project.total
totalName = span + " for " + project.name
} else {
// no project name terminator, so filter projects by name
for _, project := range report.projects {
entryTitle := project.name
if alfred.FuzzyMatches(entryTitle, name) {
item := alfred.Item{
Valid: alfred.Invalid,
Autocomplete: prefix + span + alfred.Separator + " " + entryTitle + alfred.Terminator,
Title: entryTitle,
SubtitleAll: fmt.Sprintf("%.2f", float32(project.total)/100.0),
}
if project.running {
item.Icon = "running.png"
}
items = append(items, item)
total += project.total
}
}
if name == "" {
totalName = strings.TrimRight(prefix, " ")
}
}
sort.Sort(alfred.ByTitle(items))
if totalName != "" {
item := alfred.Item{
Title: fmt.Sprintf("Total hours %s: %.2f", totalName, float32(total)/100.0),
Valid: alfred.Invalid,
Autocomplete: prefix + strings.Join(parts, alfred.Separator+" "),
SubtitleAll: alfred.Line,
}
items = alfred.InsertItem(items, item, 0)
}
}
return items, nil
}
func generateReport(since, until time.Time) (*summaryReport, error) {
log.Printf("Generating report from %s to %s", since, until)
report := summaryReport{projects: map[string]*projectEntry{}}
projects := getProjectsById()
for _, entry := range cache.Toggl.Data.TimeEntries {
start := entry.StartTime()
if !start.Before(since) && !until.Before(start) {
var projectName string
if entry.Pid == 0 {
projectName = "<No project>"
} else {
proj, _ := projects[entry.Pid]
projectName = proj.Name
log.Printf(" Project for %v: %v", entry.Pid, proj)
}
if _, ok := report.projects[projectName]; !ok {
report.projects[projectName] = &projectEntry{
name: projectName,
id: entry.Pid,
entries: map[string]*timeEntry{}}
}
project := report.projects[projectName]
duration := entry.Duration
if duration < 0 {
duration = int64(time.Now().Sub(entry.StartTime()).Seconds())
project.running = true
}
duration = roundDuration(duration)
log.Printf(" duration: %v", duration)
if _, ok := project.entries[entry.Description]; !ok {
project.entries[entry.Description] = &timeEntry{description: entry.Description}
}
if project.running {
project.entries[entry.Description].running = true
}
project.entries[entry.Description].total += duration
project.total += duration
report.total += duration
log.Printf(" report.total = %v", report.total)
}
}
return &report, nil
}
// return a datetime at the minimum time on the given date
func toDayStart(date time.Time) time.Time {
date = date.In(time.Local)
return time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
}
// return a datetime at the maximum time on the given date
func toDayEnd(date time.Time) time.Time {
date = date.In(time.Local)
return time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 999999999, time.Local)
}
// is date1's date before date2's date
func isDateBefore(date1 time.Time, date2 time.Time) bool {
return (date1.Year() == date2.Year() && date1.YearDay() < date2.YearDay()) || date1.Year() < date1.Year()
}
// is date1's date after date2's date
func isDateAfter(date1 time.Time, date2 time.Time) bool {
return (date1.Year() == date2.Year() && date2.YearDay() < date1.YearDay()) || date2.Year() < date1.Year()
}
// do date1 and date2 refer to the same date
func isSameDate(date1 time.Time, date2 time.Time) bool {
return date1.Year() == date2.Year() && date1.Month() == date2.Month() && date1.Day() == date2.Day()
}
func isSameWeek(date1 time.Time, date2 time.Time) bool {
y1, w1 := date1.ISOWeek()
y2, w2 := date2.ISOWeek()
return y1 == y2 && w1 == w2
}
func toIsoDateString(date time.Time) string {
return fmt.Sprintf("%d-%02d-%02d", date.Year(), date.Month(), date.Day())
}
func toHumanDateString(date time.Time) string {
date = date.Local()
today := time.Now()
if isSameDate(date, today) {
return "today"
} else if isSameDate(date, today.AddDate(0, 0, -1)) {
return "yesterday"
} else if isSameWeek(date, today) {
return date.Weekday().String()
} else if isDateAfter(date, today.AddDate(0, 0, -7)) {
return "last " + date.Weekday().String()
} else {
return toIsoDateString(date)
}
}
// convert a number of seconds to a fractional hour, as an int
// 1.25 hours = 125
// 0.25 hours = 25
func roundDuration(duration int64) int64 {
if config.Rounding != 0 {
incr := float64(config.Rounding * 60)
frac := 60.0 / float64(config.Rounding)
fracHours := int64(math.Ceil(float64(duration) / incr))
return fracHours * int64((100.0 / frac))
} else {
hours := float64(duration) / 3600.0
return int64(hours * 100)
}
}
type timeEntry struct {
total int64
running bool
description string
}
type projectEntry struct {
total int64
name string
id int
running bool
entries map[string]*timeEntry
}
type summaryReport struct {
total int64
projects map[string]*projectEntry
}
type byTime []toggl.TimeEntry
func (b byTime) Len() int {
return len(b)
}
func (b byTime) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
func (b byTime) Less(i, j int) bool {
if b[i].StartTime().IsZero() {
return true
} else if b[j].StartTime().IsZero() {
return false
} else {
return b[i].StartTime().Before(b[j].StartTime())
}
}
type matchEntry struct {
portion float32
start int
title string
subtitle string
id int
}
type byBestMatch []matchEntry
func (b byBestMatch) Len() int {
return len(b)
}
func (b byBestMatch) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
func (b byBestMatch) Less(i, j int) bool {
if b[i].portion < b[j].portion {
return true
}
if b[j].portion < b[i].portion {
return false
}
return false
}
type byMatchId []matchEntry
func (b byMatchId) Len() int {
return len(b)
}
func (b byMatchId) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
func (b byMatchId) Less(i, j int) bool {
return b[i].id < b[j].id
}