/
SettingsViewModel.cs
264 lines (209 loc) · 9.65 KB
/
SettingsViewModel.cs
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
254
255
256
257
258
259
260
261
262
263
264
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MpcNET.Commands.Output;
using MpcNET.Commands.Status;
using Stylophone.Common.Interfaces;
using Stylophone.Common.Services;
using Stylophone.Localization.Strings;
namespace Stylophone.Common.ViewModels
{
public partial class SettingsViewModel : ViewModelBase
{
private IApplicationStorageService _applicationStorageService;
private INotificationService _notificationService;
private IInteropService _interop;
private MPDConnectionService _mpdService;
public SettingsViewModel(MPDConnectionService mpdService, IApplicationStorageService appStorage, INotificationService notificationService, IDispatcherService dispatcherService, IInteropService interop) :
base(dispatcherService)
{
_mpdService = mpdService;
_applicationStorageService = appStorage;
_notificationService = notificationService;
_interop = interop;
}
public static new string GetHeader() => Resources.SettingsHeader;
private bool _hasInstanceBeenInitialized = false;
private int _previousUpdatingDb = 0;
[ObservableProperty]
private Theme _elementTheme;
[ObservableProperty]
private string _versionDescription;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ServerStatus))]
private string _serverInfo;
[ObservableProperty]
private string _serverHost;
[ObservableProperty]
private int _serverPort;
[ObservableProperty]
private string _serverPassword;
[ObservableProperty]
private bool _isCompactSizing;
[ObservableProperty]
private bool _isAlbumArtFetchingEnabled;
[ObservableProperty]
private bool _enableAnalytics;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsServerValid))]
[NotifyPropertyChangedFor(nameof(ServerStatus))]
private bool _isCheckingServer;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ServerStatus))]
private bool _isStreamingAvailable;
[ObservableProperty]
private bool _isLocalPlaybackEnabled;
partial void OnElementThemeChanged(Theme value)
{
Task.Run (async () => await _interop.SetThemeAsync(value));
_applicationStorageService.SetValue(nameof(ElementTheme), value.ToString());
}
partial void OnServerHostChanged(string value)
{
_applicationStorageService.SetValue(nameof(ServerHost), value ?? "localhost");
TriggerServerConnection(value, ServerPort, ServerPassword);
}
partial void OnServerPortChanged(int value)
{
_applicationStorageService.SetValue(nameof(ServerPort), value);
TriggerServerConnection(ServerHost, value, ServerPassword);
}
partial void OnServerPasswordChanged(string value)
{
_applicationStorageService.SetValue(nameof(ServerPassword), value);
TriggerServerConnection(ServerHost, ServerPort, value);
}
partial void OnIsCompactSizingChanged(bool value)
{
_applicationStorageService.SetValue(nameof(IsCompactSizing), value);
}
partial void OnIsAlbumArtFetchingEnabledChanged(bool value)
{
_applicationStorageService.SetValue(nameof(IsAlbumArtFetchingEnabled), value);
}
partial void OnEnableAnalyticsChanged(bool value)
{
_applicationStorageService.SetValue(nameof(EnableAnalytics), value);
}
public bool IsServerValid => _mpdService.IsConnected;
public string ServerStatus => IsCheckingServer ? "..." : IsServerValid ? ServerInfo?.Split('\n')?.First() + (IsStreamingAvailable ? ", "+ Resources.SettingsLocalPlaybackAvailable : "") :
Resources.SettingsNoServerError;
partial void OnIsLocalPlaybackEnabledChanged(bool value)
{
_applicationStorageService.SetValue(nameof(IsLocalPlaybackEnabled), value);
}
[RelayCommand]
private async Task ClearCacheAsync()
{
try
{
await _applicationStorageService.DeleteFolderAsync("AlbumArt");
_notificationService.ShowInAppNotification(Resources.NotificationCacheDeleted);
}
catch (Exception e)
{
_notificationService.ShowErrorNotification(e);
}
}
[RelayCommand]
private async Task RescanDbAsync()
{
if (_mpdService.CurrentStatus.UpdatingDb > 0)
{
_notificationService.ShowInAppNotification(Resources.NotificationDbAlreadyUpdating, "", NotificationType.Warning);
return;
}
var res = await _mpdService.SafelySendCommandAsync(new MpcNET.Commands.Database.UpdateCommand());
if (res != null)
_notificationService.ShowInAppNotification(Resources.NotificationDbUpdateStarted);
}
[RelayCommand]
private async Task RateAppAsync()
{
await _interop.OpenStoreReviewUrlAsync();
}
public async Task EnsureInstanceInitializedAsync()
{
if (!_hasInstanceBeenInitialized)
{
_mpdService.ConnectionChanged += async (s, e) => await UpdateServerVersionAsync();
_mpdService.StatusChanged += async (s, e) => await CheckUpdatingDbAsync();
// Initialize values directly to avoid calling CheckServerAddressAsync twice
_isCompactSizing = _applicationStorageService.GetValue<bool>(nameof(IsCompactSizing));
_serverHost = _applicationStorageService.GetValue<string>(nameof(ServerHost));
_serverHost = _serverHost?.Replace("\"", ""); // TODO: This is a quickfix for 1.x updates
_serverPort = _applicationStorageService.GetValue(nameof(ServerPort), 6600);
_enableAnalytics = _applicationStorageService.GetValue(nameof(EnableAnalytics), true);
_isAlbumArtFetchingEnabled = _applicationStorageService.GetValue(nameof(IsAlbumArtFetchingEnabled), true);
_isLocalPlaybackEnabled = _applicationStorageService.GetValue<bool>(nameof(IsLocalPlaybackEnabled));
Enum.TryParse(_applicationStorageService.GetValue<string>(nameof(ElementTheme)), out _elementTheme);
await UpdateServerVersionAsync();
VersionDescription = GetVersionDescription();
_hasInstanceBeenInitialized = true;
}
}
private async Task CheckUpdatingDbAsync()
{
var updatingDb = _mpdService.CurrentStatus.UpdatingDb;
if (_previousUpdatingDb > 0 && _previousUpdatingDb != updatingDb && updatingDb == 0)
{
// A DB update job has concluded, refresh library
await UpdateServerVersionAsync();
}
_previousUpdatingDb = updatingDb;
}
private string GetVersionDescription()
{
var appName = Resources.AppDisplayName;
Version version = _interop.GetAppVersion();
return $"{version.Major}.{version.Minor}.{(version.Revision > -1 ? version.Revision : 0)}";
}
public void RetryConnection() => TriggerServerConnection(ServerHost, ServerPort, ServerPassword);
private void TriggerServerConnection(string host, int port, string pass)
{
IsCheckingServer = true;
_mpdService.SetServerInfo(host, port, pass);
Task.Run(async () => await _mpdService.InitializeAsync());
}
private async Task UpdateServerVersionAsync()
{
IsCheckingServer = _mpdService.IsConnecting;
if (!_mpdService.IsConnected) return;
var response = await _mpdService.SafelySendCommandAsync(new StatsCommand());
if (response != null)
{
var lastUpdatedDb = DateTime.MinValue;
if (response.ContainsKey("db_update"))
{
var db_update = int.Parse(response["db_update"]);
lastUpdatedDb = DateTimeOffset.FromUnixTimeSeconds(db_update).UtcDateTime;
}
// Build info string
var outputs = await _mpdService.SafelySendCommandAsync(new OutputsCommand());
var songs = response.ContainsKey("songs") ? response["songs"] : "??";
var albums = response.ContainsKey("albums") ? response["albums"] : "??";
if (outputs != null)
{
var outputString = outputs.Select(o => o.Plugin).Aggregate((s, s2) => $"{s}, {s2}");
ServerInfo = $"MPD Protocol {_mpdService.Version}\n" +
$"{songs} Songs, {albums} Albums\n" +
$"Database last updated {lastUpdatedDb}\n" +
$"Outputs available: {outputString}";
IsStreamingAvailable = outputs.Select(o => o.Plugin).Contains("httpd");
if (!IsStreamingAvailable)
IsLocalPlaybackEnabled = false;
}
else
{
ServerInfo = $"MPD Protocol {_mpdService.Version}\n" +
$"{songs} Songs, {albums} Albums\n" +
$"Database last updated {lastUpdatedDb}";
}
}
}
}
}