-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
290 lines (250 loc) · 7.66 KB
/
main.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
//go:generate powershell -NoLogo -NoProfile -ExecutionPolicy Unrestricted -File ./.version.ps1
package main
import (
"bytes"
_ "embed"
"fmt"
"log"
"os"
"time"
"fyne.io/systray"
"github.com/BurntSushi/toml"
ico "github.com/Kodeworks/golang-image-ico"
"github.com/fogleman/gg"
"gopkg.in/resty.v1"
)
// Version info maintained by goreleaser: https://goreleaser.com/cookbooks/using-main.version/
var (
version = "0.0.0-dev"
//go:embed assets/fonts/Go-Bold.ttf
embeddedFont []byte
)
const (
configFile = "config.toml"
templateFormat = "%s: %d:%02d"
)
type togglTime struct {
hours int
minutes int
}
// Settings contains the application configuration
type Settings struct {
Token string `toml:"token"`
Email string `toml:"email"`
SyncInterval int `toml:"syncInterval"`
HighlightThreshold int `toml:"highlightThreshold"`
UserID string
Workspaces []Workspaces
}
// Workspaces stores the available toggl workspaces for the user
type Workspaces struct {
ID int32 `json:"id"`
Name string `json:"name"`
}
func main() {
unpackFont()
systray.Run(onReady, onExit)
}
func unpackFont() {
log.Printf("Unpacking font file...")
fontPath := "Go-Bold.ttf"
if _, err := os.Stat(fontPath); os.IsNotExist(err) {
if err := os.WriteFile(fontPath, embeddedFont, 0644); err != nil {
log.Fatalf("Failed to write font file to disk: %v", err)
}
}
}
func onReady() {
// Get the settings
var config Settings
_, err := toml.DecodeFile(configFile, &config)
if err != nil {
log.Fatalf("Failed to read configuration file: %v", err)
}
err = config.getUserDetail()
if err != nil {
log.Printf("Failed to get Toggl user details: %v\n", err)
}
log.Printf("- Workspaces:%v\n", config.Workspaces)
// Configure the systray item
updateIcon(0, config.HighlightThreshold)
mTitle := systray.AddMenuItem("Toggl Weekly Tracker", "Title")
mTitle.Disable()
mVersion := systray.AddMenuItem(fmt.Sprintf("v%v", version), "Version")
mVersion.Disable()
systray.AddSeparator()
systray.SetTitle("Toggl Weekly Time")
menuItems := make(map[int32]*systray.MenuItem)
for _, item := range config.Workspaces {
menuItems[item.ID] = systray.AddMenuItem(fmt.Sprintf(templateFormat, item.Name, 0, 0), item.Name)
}
menuItems[0] = systray.AddMenuItem(fmt.Sprintf(templateFormat, "Total", 0, 0), "Total")
systray.AddSeparator()
mRefresh := systray.AddMenuItem("Force Refresh", "Force Refresh the data")
systray.AddSeparator()
mQuit := systray.AddMenuItem("Quit", "Quit the app")
go func() {
for {
select {
case <-mQuit.ClickedCh:
log.Println("Application exiting...")
systray.Quit()
return
case <-mRefresh.ClickedCh:
log.Println("Manual refresh triggered...")
refreshData(&config, menuItems)
}
}
}()
go func() {
for {
refreshData(&config, menuItems)
time.Sleep(time.Duration(config.SyncInterval) * time.Minute)
}
}()
}
func refreshData(config *Settings, menuItems map[int32]*systray.MenuItem) {
totalTime := togglTime{hours: 0, minutes: 0}
for _, item := range config.Workspaces {
t, err := getWeeklyTime(config, fmt.Sprint(item.ID))
if err != nil {
log.Printf("Failed to get Toggl details: %v\n", err)
}
log.Printf("- %s [%s] time: %d:%02d\n", item.Name, fmt.Sprint(item.ID), t.hours, t.minutes)
// Set the title of the menuItem to contain the time for the individual workspace
menuItems[item.ID].SetTitle(fmt.Sprintf(templateFormat, item.Name, t.hours, t.minutes))
totalTime.add(t)
}
log.Printf("- Got new total time %d:%02d\n", totalTime.hours, totalTime.minutes)
updateIcon(int(totalTime.hours), config.HighlightThreshold)
systray.SetTooltip(fmt.Sprintf("Toggl time tracker: %d:%02d", totalTime.hours, totalTime.minutes))
menuItems[0].SetTitle(fmt.Sprintf(templateFormat, "Total", totalTime.hours, totalTime.minutes))
}
func onExit() {
// Cleaning stuff here.
}
func (c *Settings) getUserDetail() error {
type UserResponse struct {
ID int32 `json:"id"`
Workspaces []Workspaces `json:"workspaces"`
}
var ur UserResponse
toggl := resty.New().SetHostURL("https://api.track.toggl.com/api/v9").SetBasicAuth(c.Token, "api_token")
_, err := toggl.R().
SetResult(&ur).
Get("/me?with_related_data=true")
if err != nil {
return fmt.Errorf("unable to get user details from the Toggl API: %v", err)
}
c.UserID = fmt.Sprint(ur.ID)
c.Workspaces = ur.Workspaces
return nil
}
func getWeeklyTime(c *Settings, w string) (togglTime, error) {
closedTime, err := getClosedTimeEntries(c, w)
if err != nil {
return togglTime{}, fmt.Errorf("failed to get closed time entries: %v", err)
}
openTime, err := getOpenTimeEntry(c, w)
if err != nil {
return togglTime{}, fmt.Errorf("failed to get open time entry: %v", err)
}
return togglTime{
hours: getHours(closedTime + openTime),
minutes: getMinutes(closedTime + openTime),
}, nil
}
func getClosedTimeEntries(c *Settings, w string) (time.Duration, error) {
type WeeklyResponse struct {
TotalGrand int `json:"total_grand"`
}
var ct WeeklyResponse
toggleReports := resty.New().SetHostURL("https://api.track.toggl.com/reports/api/v2").SetBasicAuth(c.Token, "api_token")
_, err := toggleReports.R().
SetQueryParams(map[string]string{
"user_agent": c.Email,
"workspace_id": w,
"user_ids": c.UserID,
"since": getLastMonday(time.Now()),
}).
SetResult(&ct).
Get("/weekly")
if err != nil {
return time.Duration(0), fmt.Errorf("unable to get summary report from the Toggl API: %v", err)
}
return time.Duration(ct.TotalGrand) * time.Millisecond, nil
}
func getOpenTimeEntry(c *Settings, w string) (time.Duration, error) {
type TimeEntriesResponse struct {
WID int32 `json:"wid"`
Duration int32 `json:"duration"`
}
var ot TimeEntriesResponse
toggl := resty.New().SetHostURL("https://api.track.toggl.com/api/v9").SetBasicAuth(c.Token, "api_token")
_, err := toggl.R().
SetResult(&ot).
Get("/me/time_entries/current")
if err != nil {
return time.Duration(0), fmt.Errorf("unable to get current time entry from the Toggl API: %v", err)
}
// if the returned duration is not negative then there is no open entry.
// we also filter entries that do not match the workspace here.
if ot.Duration >= 0 || fmt.Sprint(ot.WID) != w {
return 0, nil
}
// Calculate the number of seconds based on the input data.
// Unix epoch plus returned value of duration = seconds the current entry has been running for.
od := int32(time.Now().Unix()) + ot.Duration
return time.Duration(od) * time.Second, nil
}
func getLastMonday(t time.Time) string {
delta := (int(t.Weekday()) + 6) % 7
t = t.AddDate(0, 0, -delta)
return t.Format("2006-01-02")
}
func getHours(t time.Duration) int {
d := t.Round(time.Minute)
h := d / time.Hour
return int(h)
}
func getMinutes(t time.Duration) int {
d := t.Round(time.Minute) % time.Hour
m := d / time.Minute
return int(m)
}
func (t *togglTime) add(n togglTime) {
t.minutes += n.minutes
t.hours += n.hours
if t.minutes >= 60 {
t.hours++
t.minutes -= 60
}
}
func updateIcon(hours, threshold int) {
icon, err := createIcon(16, 16, hours, threshold)
if err != nil {
log.Fatalf("Error generating icon: %v", err)
}
systray.SetIcon(icon)
}
func createIcon(x, y, hours, threshold int) ([]byte, error) {
dc := gg.NewContext(x, y)
if hours >= threshold {
// Create a red background
dc.SetHexColor("#9E0000")
dc.Clear()
}
// Add Text
dc.SetHexColor("#FFFFFF")
if err := dc.LoadFontFace("Go-Bold.ttf", 14); err != nil {
return []byte{}, err
}
dc.DrawStringAnchored(fmt.Sprintf("%v", hours), float64(x/2), float64(y/2), 0.5, 0.5)
buf := new(bytes.Buffer)
err := ico.Encode(buf, dc.Image())
if err != nil {
return []byte{}, err
}
img := buf.Bytes()
return []byte(img), nil
}