-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
420 lines (384 loc) · 9.91 KB
/
main.go
File metadata and controls
420 lines (384 loc) · 9.91 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
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
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
const hostsPath = "/etc/hosts"
const blockMarker = "# FOCUS-SYMPHONY-BLOCK"
var sitesToBlock = []string{
"www.youtube.com", "youtube.com",
"www.reddit.com", "reddit.com",
"www.twitter.com", "twitter.com", "x.com",
}
var playlist = []struct {
name string
url string
}{
{"Lofi Hip Hop - Beats to Relax/Study", "https://www.youtube.com/watch?v=jfKfPfyJRdk"},
{"Lofi Girl - Sleep Mix", "https://www.youtube.com/watch?v=rUxyKA_-grg"},
{"Dark Academia Study Music", "https://www.youtube.com/watch?v=hHW1oY26kxQ"},
{"Coding in the Rain (Ambient)", "https://www.youtube.com/watch?v=mPZkdNFkNps"},
{"Cyberpunk / Synthwave Focus Mix", "https://www.youtube.com/watch?v=qYnA9wWFHLI"},
}
var musicCmd *exec.Cmd
var currentTrack string
var sessionStart time.Time
var isShieldActive bool
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(`
____ ___ ____ _ _ _____
| __ )_ _/ ___|| | | |_ _|
| _ \| |\___ \| |_| | | |
| |_) | | ___) | _ | | |
|____/___|____/|_| |_| |_|
`)
fmt.Println("FOCUS-SYMPHONY v1.6.0 (yt-dlp Audio Engine)")
fmt.Println("--------------------------------------------")
fmt.Println()
showHelp() // FIX 1: show help menu on startup
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("fs > ")
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println()
break
}
input = strings.TrimSpace(input)
if input == "" {
continue
}
switch input {
case "start":
startSession()
case "stop":
stopSession()
case "music", "song":
playMusic()
case "stop_music":
stopMusic()
case "playlist":
showPlaylist()
case "rapid":
startRapidFocus()
case "stats":
showStats()
case "help":
showHelp()
case "exit":
stopSession()
stopMusic()
fmt.Println("Exiting. Keep Focus!")
return
default:
if len(input) == 1 && input[0] >= '1' && input[0] <= '5' {
idx := int(input[0] - '1')
playTrack(idx)
} else {
fmt.Printf("Unknown command: '%s'. Type 'help'.\n", input)
}
}
}
}
func relaunchWithSudo() {
fmt.Println(" 🔑 'start' requires elevated privileges. Re-launching with sudo...")
args := append([]string{os.Args[0]}, os.Args[1:]...)
cmd := exec.Command("sudo", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Printf(" ❌ sudo failed: %v\n", err)
}
os.Exit(0)
}
func startSession() {
if os.Getuid() != 0 {
relaunchWithSudo()
return
}
fmt.Println("⚡ Activating Acoustic Shield...")
cleanHosts()
isShieldActive = true
sessionStart = time.Now()
f, err := os.OpenFile(hostsPath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Printf(" ❌ Error: %v\n", err)
return
}
defer f.Close()
fmt.Fprintln(f, blockMarker)
for _, site := range sitesToBlock {
fmt.Fprintf(f, "127.0.0.1 %s\n", site)
fmt.Fprintf(f, "::1 %s\n", site)
}
fmt.Fprintln(f, blockMarker)
fmt.Println("✅ Sites blocked. Deep work mode active.")
fmt.Println(" Tip: type 'music' to start your focus playlist")
}
func stopSession() {
if os.Getuid() != 0 {
relaunchWithSudo()
return
}
fmt.Println("⚡ Deactivating Acoustic Shield...")
cleanHosts()
isShieldActive = false
fmt.Println("✅ World access restored.")
}
func cleanHosts() {
input, err := os.ReadFile(hostsPath)
if err != nil {
return
}
lines := strings.Split(string(input), "\n")
var newLines []string
isBlocking := false
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed == blockMarker {
isBlocking = !isBlocking
continue
}
if !isBlocking {
newLines = append(newLines, line)
}
}
// Join lines and ensure a single trailing newline if the file wasn't empty
output := strings.Join(newLines, "\n")
if len(output) > 0 && output[len(output)-1] != '\n' {
output += "\n"
}
os.WriteFile(hostsPath, []byte(output), 0644)
}
func getEffectiveUser() string {
user := os.Getenv("SUDO_USER")
if user == "" {
user = os.Getenv("USER")
}
if user == "" {
user = "nobody"
}
return user
}
func getRuntimeDir(user string) string {
out, err := exec.Command("id", "-u", user).Output()
if err != nil {
return "/run/user/1000"
}
return "/run/user/" + strings.TrimSpace(string(out))
}
func getMusicHome() string {
user := getEffectiveUser()
out, err := exec.Command("getent", "passwd", user).Output()
if err == nil {
parts := strings.Split(strings.TrimSpace(string(out)), ":")
if len(parts) >= 6 {
return parts[5]
}
}
home, _ := os.UserHomeDir()
return home
}
func buildMpvCmd(audioSrc string, user string, runtimeDir string) *exec.Cmd {
mpvArgs := []string{
"--no-video",
"--volume=80",
"--really-quiet",
"--msg-level=all=error",
audioSrc,
}
if os.Getuid() == 0 {
args := []string{"-u", user, "env",
"XDG_RUNTIME_DIR=" + runtimeDir,
"PULSE_SERVER=unix:" + runtimeDir + "/pulse/native",
"mpv",
}
args = append(args, mpvArgs...)
return exec.Command("sudo", args...)
}
cmd := exec.Command("mpv", mpvArgs...)
cmd.Env = append(os.Environ(), "XDG_RUNTIME_DIR="+runtimeDir)
return cmd
}
func detectPkgManager() (string, string) {
type pm struct {
bin string
prefix string
}
managers := []pm{
{"pacman", "sudo pacman -S"},
{"apt-get", "sudo apt-get install -y"},
{"dnf", "sudo dnf install -y"},
{"brew", "brew install"},
{"zypper", "sudo zypper install"},
{"apk", "sudo apk add"},
}
for _, m := range managers {
if _, err := exec.LookPath(m.bin); err == nil {
return m.bin, m.prefix
}
}
return "", ""
}
func depName(dep, pkgManager string) string {
if dep == "yt-dlp" {
switch pkgManager {
case "pacman":
return "yt-dlp"
case "brew":
return "yt-dlp"
default:
return "yt-dlp # or: pip3 install yt-dlp"
}
}
return dep
}
func checkDeps() bool {
ok := true
_, installCmd := detectPkgManager()
if installCmd == "" {
installCmd = "<your-package-manager>"
}
for _, dep := range []string{"mpv", "yt-dlp"} {
if _, err := exec.LookPath(dep); err != nil {
mgr, _ := detectPkgManager()
fmt.Printf(" ❌ Missing: %s\n", dep)
fmt.Printf(" Install: %s %s\n", installCmd, depName(dep, mgr))
ok = false
}
}
return ok
}
func playMusic() {
if musicCmd != nil && musicCmd.Process != nil {
fmt.Printf(" 🎵 Already playing: %s\n", currentTrack)
fmt.Println(" Type 'stop_music' to stop, or 'playlist' to pick a track.")
return
}
playTrack(rand.Intn(len(playlist)))
}
func playTrack(idx int) {
if idx < 0 || idx >= len(playlist) {
fmt.Println(" Invalid track number.")
return
}
if musicCmd != nil && musicCmd.Process != nil {
stopMusic()
}
// FIX 2: check deps and give clear guidance before attempting playback
fmt.Println(" 🔍 Checking dependencies...")
if !checkDeps() {
fmt.Println()
fmt.Println(" ⚠️ Please install missing deps above, then try again.")
fmt.Println(" Tip: yt-dlp is best installed via: pip3 install yt-dlp")
return
}
track := playlist[idx]
user := getEffectiveUser()
runtimeDir := getRuntimeDir(user)
homeDir := getMusicHome()
localPath := filepath.Join(homeDir, ".local/share/focus-symphony/assets/lofi.mp3")
audioSrc := track.url
if _, err := os.Stat(localPath); err == nil {
audioSrc = localPath
fmt.Printf("🎵 Playing local file: %s\n", filepath.Base(localPath))
} else {
fmt.Printf("🎵 Streaming: %s\n", track.name)
fmt.Println(" Resolving stream via yt-dlp... (5-10 sec)")
ytArgs := []string{"-f", "bestaudio", "--get-url", "--no-playlist", track.url}
var ytCmd *exec.Cmd
if os.Getuid() == 0 {
args := []string{"-u", user, "yt-dlp"}
args = append(args, ytArgs...)
ytCmd = exec.Command("sudo", args...)
} else {
ytCmd = exec.Command("yt-dlp", ytArgs...)
}
out, err := ytCmd.Output()
if err != nil {
fmt.Printf(" ❌ yt-dlp failed: %v\n", err)
fmt.Println(" Fix: run yt-dlp -U to update, or pip3 install -U yt-dlp")
return
}
urls := strings.Split(strings.TrimSpace(string(out)), "\n")
if len(urls) == 0 || urls[0] == "" {
fmt.Println(" ❌ No stream URL found. Video may be unavailable.")
return
}
audioSrc = urls[0]
}
musicCmd = buildMpvCmd(audioSrc, user, runtimeDir)
musicCmd.Stdout = nil
musicCmd.Stderr = nil
if err := musicCmd.Start(); err != nil {
fmt.Printf(" ❌ mpv failed to start: %v\n", err)
fmt.Println(" Fix: sudo pacman -S mpv (or your distro's equivalent)")
musicCmd = nil
return
}
currentTrack = track.name
fmt.Println(" ✅ Audio engine running. Volume: 80%")
fmt.Println(" Type 'stop_music' to stop.")
go func() {
musicCmd.Wait()
currentTrack = ""
musicCmd = nil
}()
}
func stopMusic() {
if musicCmd == nil || musicCmd.Process == nil {
fmt.Println(" (No music is currently playing.)")
return
}
musicCmd.Process.Kill()
musicCmd.Wait()
exec.Command("pkill", "-9", "-u", getEffectiveUser(), "mpv").Run()
musicCmd = nil
currentTrack = ""
fmt.Println("🎵 Audio engine offline.")
}
func showPlaylist() {
fmt.Println("\n🎵 Focus Playlists (type the number to play):")
fmt.Println()
for i, track := range playlist {
fmt.Printf(" [%d] %s\n", i+1, track.name)
}
fmt.Println()
}
func startRapidFocus() {
fmt.Println("🚀 RAPID FOCUS — 25 min Pomodoro")
startSession()
playMusic()
}
func showStats() {
if !isShieldActive {
fmt.Println(" No active focus session.")
return
}
fmt.Printf("📊 FOCUS TIME : %s\n", time.Since(sessionStart).Round(time.Second))
if currentTrack != "" {
fmt.Printf("🎵 NOW PLAYING: %s\n", currentTrack)
}
}
func showHelp() {
fmt.Println(`
Commands:
start Block distracting sites [needs sudo]
stop Unblock sites [needs sudo]
music Play a random focus track
playlist List all tracks (type 1-5 to pick)
stop_music Stop music
rapid 25-min Pomodoro + music [needs sudo]
stats Show session time + current track
help Show this menu
exit Quit
`)
}