forked from dweymouth/supersonic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservermanager.go
253 lines (229 loc) · 6.67 KB
/
servermanager.go
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
package backend
import (
"context"
"crypto/tls"
"errors"
"log"
"net/http"
"time"
"github.com/dweymouth/go-jellyfin"
"github.com/dweymouth/supersonic/backend/mediaprovider"
jellyfinMP "github.com/dweymouth/supersonic/backend/mediaprovider/jellyfin"
subsonicMP "github.com/dweymouth/supersonic/backend/mediaprovider/subsonic"
"github.com/dweymouth/supersonic/res"
"github.com/google/uuid"
"github.com/supersonic-app/go-subsonic/subsonic"
"github.com/zalando/go-keyring"
)
type ServerManager struct {
LoggedInUser string
ServerID uuid.UUID
Server mediaprovider.MediaProvider
useKeyring bool
prefetchCoverCB func(string)
appName string
config *Config
onServerConnected []func()
onLogout []func()
}
var ErrUnreachable = errors.New("server is unreachable")
func NewServerManager(appName string, config *Config, useKeyring bool) *ServerManager {
return &ServerManager{appName: appName, config: config, useKeyring: useKeyring}
}
func (s *ServerManager) SetPrefetchAlbumCoverCallback(cb func(string)) {
s.prefetchCoverCB = cb
if s.Server != nil {
s.Server.SetPrefetchCoverCallback(cb)
}
}
func (s *ServerManager) ConnectToServer(conf *ServerConfig, password string) error {
cli, err := s.connect(conf.ServerConnection, password)
if err != nil {
return err
}
s.Server = cli.MediaProvider()
s.Server.SetPrefetchCoverCallback(s.prefetchCoverCB)
s.LoggedInUser = conf.Username
s.ServerID = conf.ID
s.SetDefaultServer(s.ServerID)
for _, cb := range s.onServerConnected {
cb()
}
return nil
}
func (s *ServerManager) TestConnectionAndAuth(
ctx context.Context, connection ServerConnection, password string,
) error {
err := ErrUnreachable
done := make(chan bool)
go func() {
_, err = s.connect(connection, password)
close(done)
}()
select {
case <-ctx.Done():
return err
case <-done:
return err
}
}
func (s *ServerManager) GetDefaultServer() *ServerConfig {
for _, s := range s.config.Servers {
if s.Default {
return s
}
}
if len(s.config.Servers) > 0 {
return s.config.Servers[0]
}
return nil
}
func (s *ServerManager) SetDefaultServer(serverID uuid.UUID) {
var found bool
for _, s := range s.config.Servers {
f := s.ID == serverID
if f {
found = true
}
s.Default = f
}
if !found && len(s.config.Servers) > 0 {
s.config.Servers[0].Default = true
}
}
func (s *ServerManager) AddServer(nickname string, connection ServerConnection) *ServerConfig {
sc := &ServerConfig{
ID: uuid.New(),
Nickname: nickname,
ServerConnection: connection,
}
s.config.Servers = append(s.config.Servers, sc)
return sc
}
func (s *ServerManager) DeleteServer(serverID uuid.UUID) {
s.deleteServerPassword(serverID)
newServers := make([]*ServerConfig, 0, len(s.config.Servers)-1)
for _, s := range s.config.Servers {
if s.ID != serverID {
newServers = append(newServers, s)
}
}
s.config.Servers = newServers
}
func (s *ServerManager) Logout(deletePassword bool) {
if s.Server != nil {
if deletePassword {
s.deleteServerPassword(s.ServerID)
}
for _, cb := range s.onLogout {
cb()
}
s.Server = nil
s.LoggedInUser = ""
s.ServerID = uuid.UUID{}
}
}
func (s *ServerManager) deleteServerPassword(serverID uuid.UUID) {
if s.useKeyring {
keyring.Delete(s.appName, s.ServerID.String())
}
}
// Sets a callback that is invoked when a server is connected to.
func (s *ServerManager) OnServerConnected(cb func()) {
s.onServerConnected = append(s.onServerConnected, cb)
}
// Sets a callback that is invoked when the user logs out of a server.
func (s *ServerManager) OnLogout(cb func()) {
s.onLogout = append(s.onLogout, cb)
}
func (s *ServerManager) GetServerPassword(serverID uuid.UUID) (string, error) {
if s.useKeyring {
return keyring.Get(s.appName, serverID.String())
}
return "", errors.New("keyring not enabled")
}
func (s *ServerManager) SetServerPassword(server *ServerConfig, password string) error {
if s.useKeyring {
return keyring.Set(s.appName, server.ID.String(), password)
}
return errors.New("keyring not available")
}
func (s *ServerManager) connect(connection ServerConnection, password string) (mediaprovider.Server, error) {
var cli, altCli mediaprovider.Server
if connection.ServerType == ServerTypeJellyfin {
client, err := jellyfin.NewClient(connection.Hostname, res.AppName, res.AppVersion, jellyfin.WithTimeout(10*time.Second))
if err != nil {
log.Printf("error creating Jellyfin client: %s", err.Error())
return nil, err
}
s.checkSetInsecureSkipVerify(client.HTTPClient)
cli = &jellyfinMP.JellyfinServer{
Client: *client,
}
if connection.AltHostname != "" {
altClient, err := jellyfin.NewClient(connection.AltHostname, res.AppName, res.AppVersion, jellyfin.WithTimeout(10*time.Second))
if err != nil {
log.Printf("error creating Jellyfin alternative client: %s", err.Error())
return nil, err
}
s.checkSetInsecureSkipVerify(altClient.HTTPClient)
altCli = &jellyfinMP.JellyfinServer{
Client: *altClient,
}
}
} else {
cli = &subsonicMP.SubsonicServer{
Client: subsonic.Client{
Client: &http.Client{Timeout: 10 * time.Second},
BaseUrl: connection.Hostname,
User: connection.Username,
PasswordAuth: connection.LegacyAuth,
ClientName: res.AppName,
},
}
s.checkSetInsecureSkipVerify(cli.(*subsonicMP.SubsonicServer).Client.Client)
altCli = &subsonicMP.SubsonicServer{
Client: subsonic.Client{
Client: &http.Client{Timeout: 10 * time.Second},
BaseUrl: connection.AltHostname,
User: connection.Username,
PasswordAuth: connection.LegacyAuth,
ClientName: res.AppName,
},
}
s.checkSetInsecureSkipVerify(altCli.(*subsonicMP.SubsonicServer).Client.Client)
}
var authError error
pingChan := make(chan bool, 2) // false for primary hostname, true for alternate
pingFunc := func(delay time.Duration, cli mediaprovider.Server, val bool) {
<-time.After(delay)
resp := cli.Login(connection.Username, password)
if resp.Error != nil && !resp.IsAuthError {
return
}
authError = resp.Error
pingChan <- val // reached the server
}
go pingFunc(0, cli, false)
if connection.AltHostname != "" {
go pingFunc(333*time.Millisecond, altCli, true) // give primary hostname ping a head start
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
select {
case <-ctx.Done():
return nil, ErrUnreachable
case altPing := <-pingChan:
if altPing {
return altCli, authError
}
return cli, authError
}
}
func (s *ServerManager) checkSetInsecureSkipVerify(cli *http.Client) {
if s.config.Application.SkipSSLVerify {
cli.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
}