-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
228 lines (196 loc) · 4.99 KB
/
main.go
File metadata and controls
228 lines (196 loc) · 4.99 KB
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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
)
type AppSession struct {
AppName string `json:"app_name"`
WindowTitle string `json:"window_title"`
Duration time.Duration `json:"duration"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
}
type Tracker struct {
currentApp *AppSession
sessions []AppSession
dataFile string
}
func NewTracker(dataFile string) *Tracker {
return &Tracker{
dataFile: dataFile,
sessions: []AppSession{},
}
}
func (t *Tracker) getActiveWindow() (string, string) {
cmd := exec.Command("xdotool", "getactivewindow", "getwindowname")
output, err := cmd.Output()
if err != nil {
return "unknown", ""
}
title := strings.TrimSpace(string(output))
app := t.detectApp(title)
return app, title
}
func (t *Tracker) detectApp(title string) string {
titleLower := strings.ToLower(title)
switch {
case strings.Contains(titleLower, "brave"):
return "brave"
case strings.Contains(titleLower, "nvim"), strings.Contains(titleLower, "neovim"):
return "neovim"
case strings.Contains(titleLower, "tmux"):
return "tmux"
case strings.Contains(titleLower, "terminal"), strings.Contains(titleLower, "gnome-terminal"):
return "terminal"
case strings.Contains(titleLower, "goland"), strings.Contains(titleLower, "vscode"):
return "ide"
default:
return "other"
}
}
func (t *Tracker) track() {
app, title := t.getActiveWindow()
if t.currentApp == nil || t.currentApp.AppName != app {
// Save previous session
if t.currentApp != nil {
t.currentApp.EndTime = time.Now()
t.currentApp.Duration = time.Since(t.currentApp.StartTime)
t.sessions = append(t.sessions, *t.currentApp)
t.saveSessions()
}
// Start new session
t.currentApp = &AppSession{
AppName: app,
WindowTitle: title,
StartTime: time.Now(),
}
log.Printf("Switched to: %s - %s", app, title)
}
}
func (t *Tracker) saveSessions() {
file, err := os.Create(t.dataFile)
if err != nil {
log.Printf("Error saving data: %v", err)
return
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
if err := encoder.Encode(t.sessions); err != nil {
log.Printf("Error encoding data: %v", err)
}
}
func (t *Tracker) loadSessions() {
file, err := os.Open(t.dataFile)
if err != nil {
return // File doesn't exist yet
}
defer file.Close()
decoder := json.NewDecoder(file)
decoder.Decode(&t.sessions)
}
func (t *Tracker) generateReport() {
fmt.Println("\n=== Usage Report ===")
totals := make(map[string]time.Duration)
for _, session := range t.sessions {
totals[session.AppName] += session.Duration
}
for app, total := range totals {
hours := total.Hours()
if hours >= 1 {
fmt.Printf("%-15s: %5.1f hours\n", app, hours)
} else {
fmt.Printf("%-15s: %5.0f minutes\n", app, total.Minutes())
}
}
}
func daemonize() {
// Fork the process
if os.Getppid() != 1 {
cmd := exec.Command(os.Args[0], os.Args[1:]...)
cmd.Start()
fmt.Printf("Daemon started with PID: %d\n", cmd.Process.Pid)
// Save PID to file
pidFile := "/tmp/app-tracker.pid"
os.WriteFile(pidFile, []byte(fmt.Sprintf("%d", cmd.Process.Pid)), 0644)
os.Exit(0)
}
}
func main() {
// Handle command line arguments
if len(os.Args) > 1 {
switch os.Args[1] {
case "start":
daemonize()
return
case "report":
tracker := NewTracker("/tmp/app-usage.json")
tracker.loadSessions()
tracker.generateReport()
return
case "stop":
pidFile := "/tmp/app-tracker.pid"
data, err := os.ReadFile(pidFile)
if err != nil {
fmt.Println("Daemon not running or PID file missing")
return
}
var pid int
fmt.Sscanf(string(data), "%d", &pid)
process, err := os.FindProcess(pid)
if err != nil {
fmt.Println("Process not found")
return
}
process.Signal(syscall.SIGTERM)
os.Remove(pidFile)
fmt.Println("Daemon stopped")
return
}
}
// Default: run in foreground (for testing)
fmt.Println("Starting app tracker...")
fmt.Println("Usage:")
fmt.Println(" app-tracker start - Start daemon")
fmt.Println(" app-tracker stop - Stop daemon")
fmt.Println(" app-tracker report - Show usage report")
fmt.Println(" app-tracker - Run in foreground")
if len(os.Args) == 1 {
runTracker()
}
}
func runTracker() {
tracker := NewTracker("/tmp/app-usage.json")
tracker.loadSessions()
// Handle graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
fmt.Println("\nShutting down...")
if tracker.currentApp != nil {
tracker.currentApp.EndTime = time.Now()
tracker.currentApp.Duration = time.Since(tracker.currentApp.StartTime)
tracker.sessions = append(tracker.sessions, *tracker.currentApp)
tracker.saveSessions()
}
tracker.generateReport()
os.Exit(0)
}()
// Main tracking loop
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
tracker.track()
}
}
}