rpcfetch: config: add config mutex

The GUI will need to update configuration, so now conf is thread safe.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
This commit is contained in:
Ophestra Umiker 2024-06-21 12:33:18 +09:00
parent 101b997771
commit 72d6a8e95c
Signed by: cat
SSH Key Fingerprint: SHA256:gQ67O0enBZ7UdZypgtspB2FDM1g3GVw8nX0XSdcFw8Q
3 changed files with 44 additions and 25 deletions

View File

@ -1,12 +1,10 @@
package main
import (
"encoding/gob"
"errors"
"fmt"
"log"
"os"
"path"
"strconv"
"strings"
"time"
@ -63,6 +61,7 @@ func (s *applyState) replace(t string) string {
}
func apply() {
confLock.RLock()
act := *conf.Activity
s := &applyState{}
@ -74,6 +73,7 @@ func apply() {
SmallImage: act.Assets.SmallImage,
SmallText: s.replace(act.Assets.SmallText),
}
confLock.RUnlock()
if nonce, err := retry(&act); err != nil {
log.Fatalf("error setting activity: %s", err)
@ -82,27 +82,6 @@ func apply() {
}
}
func save() {
nf, err := os.CreateTemp(path.Dir(confPath), ".rpcfetch.conf.*")
if err != nil {
log.Fatalf("error creating temporary configuration file: %s", err)
}
if err = gob.NewEncoder(nf).Encode(defaultConfig); err != nil {
fmt.Printf("error writing configuration file: %s\n", err)
os.Exit(1)
}
if err = nf.Close(); err != nil {
log.Fatalf("error closing temporary configuration file: %s", err)
}
if err = os.Rename(nf.Name(), confPath); err != nil {
log.Fatalf("error renaming configuration file: %s", err)
}
log.Printf("saved configuration to %s", confPath)
}
func retry(act *rpcfetch.Activity) (string, error) {
try:
nonce, err := d.SetActivity(act)

View File

@ -1,14 +1,55 @@
package main
import (
"encoding/gob"
"fmt"
"log"
"os"
"path"
"sync"
"git.ophivana.moe/cat/rpcfetch"
)
var (
conf *config
confLock = &sync.RWMutex{}
)
type config struct {
ID string
Activity *rpcfetch.Activity
}
func (c *config) write(v config) {
confLock.Lock()
*c = v
confLock.Unlock()
}
func save() {
nf, err := os.CreateTemp(path.Dir(confPath), ".rpcfetch.conf.*")
if err != nil {
log.Fatalf("error creating temporary configuration file: %s", err)
}
confLock.RLock()
if err = gob.NewEncoder(nf).Encode(defaultConfig); err != nil {
fmt.Printf("error writing configuration file: %s\n", err)
os.Exit(1)
}
confLock.RUnlock()
if err = nf.Close(); err != nil {
log.Fatalf("error closing temporary configuration file: %s", err)
}
if err = os.Rename(nf.Name(), confPath); err != nil {
log.Fatalf("error renaming configuration file: %s", err)
}
log.Printf("saved configuration to %s", confPath)
}
// sample config so the program works out of the box
var defaultConfig = config{
ID: "1252927154480611351",

View File

@ -14,7 +14,6 @@ import (
var (
d *rpcfetch.Client
conf config
confPath string
)
@ -33,7 +32,7 @@ func main() {
// use defaults
log.Print("configuration file does not exist, using defaults")
conf = defaultConfig
conf = &defaultConfig
} else {
// decode from existing file
if err = gob.NewDecoder(cf).Decode(&conf); err != nil {