aboutsummaryrefslogtreecommitdiff
path: root/src/page_config.go
blob: ed64f58fabbd3dc8e74caa49f1c1cf129df38aca (plain)
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
package src

import (
	"fmt"
	"net/http"

	"github.com/delucks/go-subsonic"
	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
)

func (a *app) configPage() *tview.Form {
	var err error

	form := tview.NewForm().
		AddInputField("Server URL", a.cfg.BaseURL, 40, nil, func(txt string) { a.cfg.BaseURL = txt }).
		AddInputField("Username", a.cfg.Username, 20, nil, func(txt string) { a.cfg.Username = txt }).
		AddPasswordField("Password", a.cfg.Password, 20, '*', func(txt string) { a.cfg.Password = txt }).
		AddButton("Test", func() {
			if err = testConfig(a.cfg); err != nil {
				a.alert("Could not auth: %v", err)
			} else {
				a.alert("Success.")
			}
		}).
		AddButton("Save", func() {
			err := a.cfg.Save()
			if err != nil {
				a.alert("Error saving: %v", err)
				return
			}

			a.sub, err = buildSubsonicClient(a.cfg)
			if err != nil {
				a.alert("Could not auth: %v", err)
			} else {
				a.alert("All good!")
			}
		})

	form.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		if event.Key() == tcell.KeyCtrlR {
			if err := a.refreshArtists(); err != nil {
				a.alert("Error: %v", err)
				return nil
			}

			if err := a.refreshPlaylists(); err != nil {
				a.alert("Error: %v", err)
				return nil
			}

			a.alert("Refreshed successfully")

			return nil
		}

		return event
	})

	return form
}

func testConfig(cfg *Config) error {
	if cfg.BaseURL == "" {
		return fmt.Errorf("empty base URL")
	}

	if cfg.Username == "" {
		return fmt.Errorf("empty username")
	}

	if cfg.Password == "" {
		return fmt.Errorf("empty password")
	}

	_, err := buildSubsonicClient(cfg)
	return err
}

func buildSubsonicClient(cfg *Config) (*subsonic.Client, error) {
	tmpSub := &subsonic.Client{
		Client:       http.DefaultClient,
		BaseUrl:      cfg.BaseURL,
		User:         cfg.Username,
		ClientName:   "termsonic",
		PasswordAuth: true,
	}

	err := tmpSub.Authenticate(cfg.Password)
	if err != nil {
		return nil, err
	}

	return tmpSub, nil
}