MirrorBar Plus 13: Claude and Grok flyout, clipboard history button, mp3 player
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JW57Zw8fvgzpeDkbUYT7sG
This commit is contained in:
@@ -0,0 +1,353 @@
|
||||
package main
|
||||
|
||||
// The mp3 and audiobook player. MirrorBar runs a tiny web server that listens
|
||||
// only on this PC (127.0.0.1), serves the player page and the audio files from
|
||||
// the folder you picked, and remembers where you were: which file, how far in,
|
||||
// the volume and the speed, separately for every folder or file you have played.
|
||||
// The window itself is a small Edge app window (see webfly.go).
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var audioExts = map[string]string{
|
||||
".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".m4b": "audio/mp4", ".aac": "audio/aac",
|
||||
".ogg": "audio/ogg", ".oga": "audio/ogg", ".opus": "audio/ogg", ".wav": "audio/wav", ".flac": "audio/flac",
|
||||
}
|
||||
|
||||
type playSpot struct {
|
||||
Index int `json:"index"`
|
||||
Pos float64 `json:"pos"`
|
||||
}
|
||||
|
||||
type playerState struct {
|
||||
Source string `json:"source"` // folder or single file
|
||||
Vol float64 `json:"vol"`
|
||||
Rate float64 `json:"rate"`
|
||||
Spots map[string]playSpot `json:"spots"`
|
||||
}
|
||||
|
||||
var (
|
||||
plMu sync.Mutex
|
||||
plState = playerState{Vol: 1, Rate: 1, Spots: map[string]playSpot{}}
|
||||
plFiles []string // full paths, in play order
|
||||
plLoaded bool
|
||||
plPort int
|
||||
plStart sync.Once
|
||||
)
|
||||
|
||||
func playerStateFile() string { return filepath.Join(dataDir(), "player.json") }
|
||||
|
||||
func playerLoad() {
|
||||
if plLoaded {
|
||||
return
|
||||
}
|
||||
plLoaded = true
|
||||
if b, err := os.ReadFile(playerStateFile()); err == nil {
|
||||
var s playerState
|
||||
if json.Unmarshal(b, &s) == nil {
|
||||
if s.Spots == nil {
|
||||
s.Spots = map[string]playSpot{}
|
||||
}
|
||||
if s.Vol <= 0 || s.Vol > 1 {
|
||||
s.Vol = 1
|
||||
}
|
||||
if s.Rate < 0.5 || s.Rate > 3 {
|
||||
s.Rate = 1
|
||||
}
|
||||
plState = s
|
||||
}
|
||||
}
|
||||
plFiles = scanAudio(plState.Source)
|
||||
}
|
||||
|
||||
func playerSave() {
|
||||
b, err := json.Marshal(plState)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.MkdirAll(dataDir(), 0o755)
|
||||
_ = os.WriteFile(playerStateFile(), b, 0o644)
|
||||
}
|
||||
|
||||
func isAudio(p string) bool {
|
||||
_, ok := audioExts[strings.ToLower(filepath.Ext(p))]
|
||||
return ok
|
||||
}
|
||||
|
||||
// scanAudio lists the audio in a folder (sub folders too) in natural order, so
|
||||
// "Chapter 2" comes before "Chapter 10", or returns the one file itself.
|
||||
func scanAudio(src string) []string {
|
||||
if src == "" {
|
||||
return nil
|
||||
}
|
||||
st, err := os.Stat(src)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if !st.IsDir() {
|
||||
if isAudio(src) {
|
||||
return []string{src}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
_ = filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if !d.IsDir() && isAudio(p) && len(out) < 5000 {
|
||||
out = append(out, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.SliceStable(out, func(i, j int) bool { return naturalLess(out[i], out[j]) })
|
||||
return out
|
||||
}
|
||||
|
||||
func naturalLess(a, b string) bool {
|
||||
a, b = strings.ToLower(a), strings.ToLower(b)
|
||||
i, j := 0, 0
|
||||
for i < len(a) && j < len(b) {
|
||||
if unicode.IsDigit(rune(a[i])) && unicode.IsDigit(rune(b[j])) {
|
||||
si := i
|
||||
for i < len(a) && unicode.IsDigit(rune(a[i])) {
|
||||
i++
|
||||
}
|
||||
sj := j
|
||||
for j < len(b) && unicode.IsDigit(rune(b[j])) {
|
||||
j++
|
||||
}
|
||||
na, nb := strings.TrimLeft(a[si:i], "0"), strings.TrimLeft(b[sj:j], "0")
|
||||
if len(na) != len(nb) {
|
||||
return len(na) < len(nb)
|
||||
}
|
||||
if na != nb {
|
||||
return na < nb
|
||||
}
|
||||
continue
|
||||
}
|
||||
if a[i] != b[j] {
|
||||
return a[i] < b[j]
|
||||
}
|
||||
i++
|
||||
j++
|
||||
}
|
||||
return len(a)-i < len(b)-j
|
||||
}
|
||||
|
||||
func trackName(src, p string) string {
|
||||
rel := p
|
||||
if st, err := os.Stat(src); err == nil && st.IsDir() {
|
||||
if r, err := filepath.Rel(src, p); err == nil {
|
||||
rel = r
|
||||
}
|
||||
} else {
|
||||
rel = filepath.Base(p)
|
||||
}
|
||||
rel = strings.TrimSuffix(rel, filepath.Ext(rel))
|
||||
return strings.ReplaceAll(rel, string(filepath.Separator), " / ")
|
||||
}
|
||||
|
||||
type playerView struct {
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Tracks []string `json:"tracks"`
|
||||
Index int `json:"index"`
|
||||
Pos float64 `json:"pos"`
|
||||
Vol float64 `json:"vol"`
|
||||
Rate float64 `json:"rate"`
|
||||
}
|
||||
|
||||
func playerViewNow() playerView {
|
||||
v := playerView{Source: plState.Source, Vol: plState.Vol, Rate: plState.Rate, Tracks: []string{}}
|
||||
if plState.Source != "" {
|
||||
v.Name = filepath.Base(plState.Source)
|
||||
if v.Name == "" || v.Name == "." || v.Name == string(filepath.Separator) {
|
||||
v.Name = plState.Source
|
||||
}
|
||||
}
|
||||
for _, p := range plFiles {
|
||||
v.Tracks = append(v.Tracks, trackName(plState.Source, p))
|
||||
}
|
||||
if sp, ok := plState.Spots[plState.Source]; ok && sp.Index >= 0 && sp.Index < len(plFiles) {
|
||||
v.Index, v.Pos = sp.Index, sp.Pos
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func playerURL() string {
|
||||
plStart.Do(playerServe)
|
||||
return fmt.Sprintf("http://127.0.0.1:%d/", plPort)
|
||||
}
|
||||
|
||||
func playerServe() {
|
||||
plMu.Lock()
|
||||
playerLoad()
|
||||
plMu.Unlock()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
plPort = ln.Addr().(*net.TCPAddr).Port
|
||||
mux := http.NewServeMux()
|
||||
guard := func(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// only this program's own page may talk to the server
|
||||
if r.Host != fmt.Sprintf("127.0.0.1:%d", plPort) {
|
||||
http.Error(w, "no", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
h(w, r)
|
||||
}
|
||||
}
|
||||
mux.HandleFunc("/", guard(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_, _ = w.Write([]byte(playerPage))
|
||||
}))
|
||||
mux.HandleFunc("/api/state", guard(func(w http.ResponseWriter, r *http.Request) {
|
||||
plMu.Lock()
|
||||
v := playerViewNow()
|
||||
plMu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}))
|
||||
mux.HandleFunc("/api/file", guard(func(w http.ResponseWriter, r *http.Request) {
|
||||
var i int
|
||||
fmt.Sscanf(r.URL.Query().Get("i"), "%d", &i)
|
||||
plMu.Lock()
|
||||
var p string
|
||||
if i >= 0 && i < len(plFiles) {
|
||||
p = plFiles[i]
|
||||
}
|
||||
plMu.Unlock()
|
||||
if p == "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
ct := audioExts[strings.ToLower(filepath.Ext(p))]
|
||||
if ct == "" {
|
||||
ct = mime.TypeByExtension(filepath.Ext(p))
|
||||
}
|
||||
w.Header().Set("Content-Type", ct)
|
||||
http.ServeContent(w, r, filepath.Base(p), st.ModTime(), f)
|
||||
}))
|
||||
mux.HandleFunc("/api/save", guard(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Index int `json:"index"`
|
||||
Pos float64 `json:"pos"`
|
||||
Vol float64 `json:"vol"`
|
||||
Rate float64 `json:"rate"`
|
||||
}
|
||||
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&in) != nil {
|
||||
http.Error(w, "bad", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
plMu.Lock()
|
||||
if plState.Source != "" {
|
||||
plState.Spots[plState.Source] = playSpot{Index: in.Index, Pos: in.Pos}
|
||||
}
|
||||
if in.Vol >= 0 && in.Vol <= 1 {
|
||||
plState.Vol = in.Vol
|
||||
}
|
||||
if in.Rate >= 0.5 && in.Rate <= 3 {
|
||||
plState.Rate = in.Rate
|
||||
}
|
||||
playerSave()
|
||||
plMu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
mux.HandleFunc("/api/pick", guard(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "no", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
playerPick(r.URL.Query().Get("kind") == "folder")
|
||||
plMu.Lock()
|
||||
v := playerViewNow()
|
||||
plMu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}))
|
||||
go func() { _ = http.Serve(ln, mux) }()
|
||||
}
|
||||
|
||||
// playerPick opens a standard Windows folder or file dialog (through PowerShell,
|
||||
// which is on every Windows 11 PC), then loads what was picked.
|
||||
func playerPick(folder bool) {
|
||||
if !pickBusy.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
defer pickBusy.Store(false)
|
||||
script := `Add-Type -AssemblyName System.Windows.Forms
|
||||
$o = New-Object System.Windows.Forms.Form
|
||||
$o.TopMost = $true
|
||||
$o.ShowInTaskbar = $false
|
||||
$o.StartPosition = 'CenterScreen'
|
||||
$o.Size = New-Object System.Drawing.Size(1,1)
|
||||
$o.Opacity = 0
|
||||
$o.Show()
|
||||
$o.Activate()
|
||||
`
|
||||
if folder {
|
||||
script += `$d = New-Object System.Windows.Forms.FolderBrowserDialog
|
||||
$d.Description = 'Pick the folder with your music or audiobook'
|
||||
$d.ShowNewFolderButton = $false
|
||||
if ($d.ShowDialog($o) -eq 'OK') { [Console]::Out.Write($d.SelectedPath) }`
|
||||
} else {
|
||||
script += `$d = New-Object System.Windows.Forms.OpenFileDialog
|
||||
$d.Title = 'Pick an audio file'
|
||||
$d.Filter = 'Audio files|*.mp3;*.m4a;*.m4b;*.aac;*.ogg;*.oga;*.opus;*.wav;*.flac|All files|*.*'
|
||||
if ($d.ShowDialog($o) -eq 'OK') { [Console]::Out.Write($d.FileName) }`
|
||||
}
|
||||
script += "\n$o.Close()"
|
||||
cmd := exec.Command("powershell.exe", "-NoProfile", "-STA", "-WindowStyle", "Hidden", "-Command", script)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
src := strings.TrimSpace(string(out))
|
||||
if src == "" {
|
||||
return
|
||||
}
|
||||
files := scanAudio(src)
|
||||
plMu.Lock()
|
||||
defer plMu.Unlock()
|
||||
if len(files) == 0 {
|
||||
return
|
||||
}
|
||||
plState.Source = src
|
||||
plFiles = files
|
||||
playerSave()
|
||||
}
|
||||
Reference in New Issue
Block a user