Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
softwarespot committed Oct 26, 2024
0 parents commit a8fe785
Show file tree
Hide file tree
Showing 20 changed files with 512 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# This workflow will build a golang project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go

name: Go
on: [push, pull_request]

jobs:
test:
strategy:
matrix:
go-version: [1.23.x]

runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}

- name: Test
run: go test -cover -v ./...
31 changes: 31 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Taken from URL: https://github.com/github/gitignore/blob/main/Go.gitignore
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

# Go workspace file
go.work
go.work.sum

# env file
.env

# Misc
bin/
pausefy
pid
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024 SoftwareSpot Apps

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
27 changes: 27 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
TARGETS_LINUX=pausefy-linux

TARGETS_ALL=$(TARGETS_LINUX)
OS_BUILDS=build-linux

all: $(OS_BUILDS)

# Linux
build-linux: GOOS=linux
build-linux: GOARCH=amd64
build-linux: $(TARGETS_LINUX)

pausefy%:
@echo building to bin/$@
@CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) go build -o bin/$@

clean:
@cd bin && $(RM) $(TARGETS_ALL)

start:
@./stop.sh
@./start.sh

stop:
@./stop.sh

.PHONY: clean start stop
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Pausefy

![Go Tests](https://github.com/softwarespot/pausefy/actions/workflows/go.yml/badge.svg)

Pause Spotify when the `mute` key on the keyboard is pressed for Debian based OS'es

![Demo](pausefy-anime.gif)

## Prerequisites

- Debian based OS e.g. Ubuntu
- go 1.23.0 or above
- Spotify installed from https://www.spotify.com/us/download/linux/ (**NOT** the snap version)
- make

## Build

Build the binary to `./bin` as the executable `pausefy-linux`

```bash
make
```

## Start and stop

**NOTE: Ensure the application is built before executing the script**

Starts the application defined in `./bin/pausefy-linux` as a background process and stores the process ID (PID) to the file `pid` (current working directory). The process output i.e. STDOUT is written to the file `nohup.out` in the current working directory

```bash
make start
```

Stops the application defined in `./bin/pausefy-linux`, using the process ID (PID) stored in the file `pid` (current working directory) as well as removing the files `pid` and `nohup.out` in the current working directory

```bash
make stop
```

## Linting

Docker

```bash
docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:latest golangci-lint run -v --tests=false --disable-all -E durationcheck,errorlint,exhaustive,gocritic,gosimple,ineffassign,misspell,predeclared,revive,staticcheck,unparam,unused,whitespace --max-issues-per-linter=10000 --max-same-issues=10000
```

Local

```bash
golangci-lint run --tests=false --disable-all -E durationcheck,errorlint,exhaustive,gocritic,gosimple,ineffassign,misspell,predeclared,revive,staticcheck,unparam,unused,whitespace --max-issues-per-linter=10000 --max-same-issues=10000
```

## License

The code has been licensed under the [MIT](https://opensource.org/license/mit) license.
15 changes: 15 additions & 0 deletions cmd/execute.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package cmd

import "flag"

func Execute() {
var showHelp bool
flagBoolVarP(&showHelp, "help", "h", false, "Display the help text and exit")

flag.Parse()

if showHelp {
cmdHelp()
}
cmdStart()
}
16 changes: 16 additions & 0 deletions cmd/help.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package cmd

import "fmt"

func cmdHelp() {
helpText := `Usage: ./pausefy-linux [OPTIONS]
Pause Spotify when the "mute" key on the keyboard is pressed for Debian based OS'es
Options:
-h, --help Show this help text and exit.
Examples:
./pausefy-linux`
fmt.Println(helpText)
}
9 changes: 9 additions & 0 deletions cmd/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package cmd

import "flag"

// The naming has been taken from "pflag" i.e. used in "cobra". URL: https://pkg.go.dev/github.com/spf13/pflag#BoolVarP
func flagBoolVarP(p *bool, name, shorthand string, value bool, usage string) {
flag.BoolVar(p, name, value, usage)
flag.BoolVar(p, shorthand, value, usage)
}
82 changes: 82 additions & 0 deletions cmd/start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package cmd

import (
"log"
"time"

"pausefy/internal/helpers"
"pausefy/internal/spotify"
"pausefy/internal/volume"

"github.com/pkg/errors"
)

func cmdStart() {
// DISCLAIMER: Given the nature of the application, errors which occur can just be logged to STDOUT, as the application
// shouldn't exit and can recover eventually, for example when Spotify has started/re-started

helpers.Retry(func(iter int) error {
sfy, err := spotify.New()
if err != nil {
return errors.Wrapf(err, "Spotify not running. Try %d", iter)
}

monitorFn, err := getMonitorFunc(sfy)
if err != nil {
return errors.Wrapf(err, "creating monitor function. Try %d", iter)
}

log.Printf("start monitoring %s\n", helpers.ExecutableName())
if err := volume.Monitor(monitorFn); err != nil {
return errors.Wrapf(err, "start speaker monitoring. Try %d", iter)
}
return nil
}, 5*time.Second)
}

func getMonitorFunc(sfy *spotify.App) (volume.MonitorFunc, error) {
currSpotifyStatus, err := sfy.Status()
if err != nil {
return nil, errors.Wrap(err, "get Spotify status")
}

return func(speakerStatus volume.Status) {
// Handle errors by logging to STDOUT,
// as there is no reason to exit the application, as this is likely temporary

isRunning, err := sfy.IsRunning()
if err != nil {
log.Printf("speaker status changed to %q, got an error whilst checking if Spotify is running\n", speakerStatus)
log.Println(err)
return
}

if !isRunning {
log.Printf("speaker status changed to %q, Spotify is not running\n", speakerStatus)
return
}

switch speakerStatus {
case volume.StatusOn:
if currSpotifyStatus == spotify.StatusPlaying {
log.Printf("speaker status changed to %q, setting Spotify to play\n", speakerStatus)
if err := sfy.Play(); err != nil {
log.Println(err)
}
} else {
log.Printf("speaker status changed to %q, not setting Spotify to play\n", speakerStatus)
}
case volume.StatusOff:
log.Printf("speaker status changed to %q, setting Spotify to pause\n", speakerStatus)
if err := sfy.Pause(); err != nil {
log.Println(err)
}
case volume.StatusUnknown:
log.Println("unable to determine the current speaker status")
}

if currSpotifyStatus, err = sfy.Status(); err != nil {
log.Println(err)
}
}, nil
}
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module pausefy

go 1.23.0

require (
github.com/godbus/dbus/v5 v5.1.0
github.com/pkg/errors v0.9.1
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
19 changes: 19 additions & 0 deletions internal/helpers/exec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package helpers

import (
"os"
"os/exec"
"strings"

"github.com/pkg/errors"
)

func ExecCmd(args []string) (string, error) {
cmd := exec.Command(args[0], args[1:]...)
cmd.Env = os.Environ()
out, err := cmd.Output()
if err != nil {
return "", errors.Wrapf(err, "error executing %q", strings.Join(args, " "))
}
return string(out), nil
}
10 changes: 10 additions & 0 deletions internal/helpers/executable_name.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package helpers

import (
"os"
"path/filepath"
)

func ExecutableName() string {
return filepath.Base(os.Args[0])
}
17 changes: 17 additions & 0 deletions internal/helpers/retry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package helpers

import (
"log"
"time"
)

func Retry(fn func(int) error, retriesWait time.Duration) {
for currIter := 1; ; currIter++ {
if err := fn(currIter); err != nil {
log.Println(err)
time.Sleep(retriesWait)
continue
}
return
}
}
Loading

0 comments on commit a8fe785

Please sign in to comment.