-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmain.go
More file actions
206 lines (181 loc) · 5.22 KB
/
Copy pathmain.go
File metadata and controls
206 lines (181 loc) · 5.22 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
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
"github.com/msfoundry/commit/extraction"
"github.com/msfoundry/commit/server"
"github.com/msfoundry/commit/store"
"github.com/msfoundry/commit/whatsapp"
waStore "go.mau.fi/whatsmeow/store"
)
const defaultPort = 9384
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
waStore.SetOSInfo("Commit", [3]uint32{1, 1, 1})
dataDir, err := dataDirectory()
if err != nil {
log.Fatalf("failed to determine data directory: %v", err)
}
if err := os.MkdirAll(dataDir, 0700); err != nil {
log.Fatalf("failed to create data directory: %v", err)
}
setupLogFile(dataDir)
db, err := store.Open(filepath.Join(dataDir, "commit.db"))
if err != nil {
log.Fatalf("failed to open database: %v", err)
}
defer db.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
extractor := extraction.New(db, nil)
if len(os.Args) > 1 && os.Args[1] == "sweep" {
fmt.Println("Running resolution sweep...")
extractor.RunStalenessCheck()
if err := extractor.RunResolutionSweep(ctx); err != nil {
log.Fatalf("sweep error: %v", err)
}
fmt.Println("Done.")
return
}
wa := whatsapp.New(db, dataDir, extractor, ctx)
wa.SetFindHandler(extractor)
wa.InitScheduler(db)
extractor.SetNotifier(wa)
srv := server.New(db, wa, extractor, defaultPort)
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh
log.Println("shutting down...")
cancel()
}()
if db.GetAPIKey() != "" && wa.HasSession() {
go wa.Connect(ctx)
}
hasHostsEntry := ensureHostsEntry()
dashboardURL := fmt.Sprintf("http://localhost:%d", defaultPort)
if hasHostsEntry {
dashboardURL = fmt.Sprintf("http://commit:%d", defaultPort)
}
addr := fmt.Sprintf("0.0.0.0:%d", defaultPort)
ln, err := net.Listen("tcp", addr)
if err != nil {
// Single-instance behavior: if another Commit already owns the port,
// just bring up its dashboard and exit quietly. A Fatalf here is
// invisible when launched from Finder.
if resp, herr := http.Get(fmt.Sprintf("http://localhost:%d/api/version", defaultPort)); herr == nil {
resp.Body.Close()
log.Printf("another Commit instance is already running — opening its dashboard")
openBrowser(dashboardURL)
return
}
log.Fatalf("failed to listen on %s: %v", addr, err)
}
log.Printf("Commit running at %s", dashboardURL)
openBrowser(dashboardURL)
// Headless mode: no menu bar / tray icon, server blocks on main.
if os.Getenv("COMMIT_NO_TRAY") == "1" {
if err := srv.Serve(ctx, ln); err != nil {
log.Fatalf("server error: %v", err)
}
return
}
// The tray owns the main thread (AppKit requirement on macOS);
// the HTTP server runs alongside it.
go func() {
err := srv.Serve(ctx, ln)
if err != nil {
log.Printf("server error: %v", err)
}
// If the server stops for any reason, take the tray down with it —
// a menu bar icon without a working dashboard is a zombie.
cancel()
quitTray()
}()
runTray(ctx, cancel, db, wa, extractor, dashboardURL)
}
func ensureHostsEntry() bool {
if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {
return false
}
data, err := os.ReadFile("/etc/hosts")
if err != nil {
return false
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
for _, f := range fields[1:] {
if f == "commit" {
return true
}
}
}
log.Println("Adding 'commit' to /etc/hosts (one-time setup, requires admin password)...")
script := `do shell script "echo '127.0.0.1 commit' >> /etc/hosts" with administrator privileges`
cmd := exec.Command("osascript", "-e", script)
if err := cmd.Run(); err != nil {
log.Printf("Could not add hosts entry: %v (you can still use localhost:%d)", err, defaultPort)
return false
}
log.Println("Added 'commit' to /etc/hosts — use http://commit:" + fmt.Sprint(defaultPort))
return true
}
func openBrowser(url string) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("open", url)
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
default:
cmd = exec.Command("xdg-open", url)
}
if err := cmd.Start(); err != nil {
log.Printf("Could not open browser: %v — open %s manually", err, url)
}
}
func setupLogFile(dataDir string) {
logPath := filepath.Join(dataDir, "commit.log")
if info, err := os.Stat(logPath); err == nil && info.Size() > 5*1024*1024 {
os.Rename(logPath, logPath+".old")
}
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
log.Printf("could not open log file: %v (logging to stderr only)", err)
return
}
log.SetOutput(io.MultiWriter(os.Stderr, f))
log.Printf("=== Commit starting ===")
}
func dataDirectory() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
newDir := filepath.Join(home, ".commit")
oldDir := filepath.Join(home, ".owe")
if _, err := os.Stat(newDir); os.IsNotExist(err) {
if _, err := os.Stat(oldDir); err == nil {
os.Rename(oldDir, newDir)
}
}
return newDir, nil
}