forked from ycastonguay/MPfm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SyncClientService.cs
362 lines (307 loc) · 14.6 KB
/
SyncClientService.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Copyright © 2011-2013 Yanick Castonguay
//
// This file is part of Sessions.
//
// Sessions is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Sessions is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Sessions. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using Sessions.Library.Objects;
using Sessions.Library.Services.Interfaces;
using Sessions.Core;
using Sessions.Core.Network;
using Sessions.Sound.AudioFiles;
namespace Sessions.Library.Services
{
public class SyncClientService : ISyncClientService
{
readonly ILibraryService _libraryService;
readonly IAudioFileCacheService _audioFileCacheService;
readonly ISyncDeviceSpecifications _deviceSpecifications;
Stopwatch _stopwatch;
WebClientTimeout _webClient;
long _bytesDownloaded = 0;
int _filesDownloaded = 0;
int _errorCount = 0;
List<AudioFile> _audioFiles = new List<AudioFile>();
long _lastBytesReceived = 0;
public SyncDevice CurrentDevice { get; private set; }
public event ReceivedIndex OnReceivedIndex;
public event DownloadIndexProgress OnDownloadIndexProgress;
public event DownloadAudioFileStatus OnDownloadAudioFileStarted;
public event DownloadAudioFileStatus OnDownloadAudioFileProgress;
public event DownloadAudioFileStatus OnDownloadAudioFileCompleted;
public event EventHandler OnDownloadAudioFilesCompleted;
public SyncClientService(ILibraryService libraryService, IAudioFileCacheService audioFileCacheService, ISyncDeviceSpecifications deviceSpecifications)
{
_libraryService = libraryService;
_audioFileCacheService = audioFileCacheService;
_deviceSpecifications = deviceSpecifications;
Initialize();
}
private void Initialize()
{
_stopwatch = new Stopwatch();
_webClient = new WebClientTimeout(3000);
_webClient.DownloadProgressChanged += HandleDownloadProgressChanged;
_webClient.DownloadStringCompleted += HandleDownloadStringCompleted;
_webClient.DownloadFileCompleted += HandleDownloadFileCompleted;
}
private string GetDownloadSpeed()
{
float speed = ((float)_bytesDownloaded / 1000) / ((float)_stopwatch.ElapsedMilliseconds / 1000);
return string.Format("{0:0}kb/s", speed);
}
private void HandleDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//Console.WriteLine("SyncClientService - HandleDownloadProgressChanged - progressPercentage: {0} bytesReceived: {1} totalBytesToReceive: {2}", e.ProgressPercentage, e.BytesReceived, e.TotalBytesToReceive);
string fileName = string.Empty;
if(_audioFiles != null && _audioFiles.Count >= _filesDownloaded+1)
fileName = Path.GetFileName(_audioFiles[_filesDownloaded].FilePath);
_bytesDownloaded += e.BytesReceived - _lastBytesReceived;
_lastBytesReceived = e.BytesReceived;
if (OnDownloadIndexProgress != null)
OnDownloadIndexProgress(e.ProgressPercentage, e.BytesReceived, e.TotalBytesToReceive);
if (OnDownloadAudioFileProgress != null)
OnDownloadAudioFileProgress(new SyncClientDownloadAudioFileProgressEntity(){
Status = "Downloading files...",
PercentageDone = ((float)_filesDownloaded / (float)_audioFiles.Count()) * 100f,
FilesDownloaded = _filesDownloaded,
TotalFiles = _audioFiles.Count(),
DownloadBytesReceived = e.BytesReceived,
DownloadTotalBytesToReceive = e.TotalBytesToReceive,
DownloadPercentageDone = ((float)e.BytesReceived / (float)e.TotalBytesToReceive) * 100f,
DownloadSpeed = GetDownloadSpeed(),
Errors = _errorCount,
DownloadFileName = fileName,
Log = string.Empty
});
}
private void HandleDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Cancelled)
return;
if (e.Error != null)
{
Console.WriteLine("SyncClientService - HandleDownloadStringCompleted - Error: {0}", e.Error);
if (OnReceivedIndex != null)
OnReceivedIndex(e.Error);
return;
}
var requestType = (RequestTypes)e.UserState;
switch (requestType)
{
case RequestTypes.DownloadIndex:
Console.WriteLine("SyncClientService - Finished downloading index. Deserializing XML...");
_audioFiles = XmlSerialization.Deserialize<List<AudioFile>>(e.Result);
Console.WriteLine("SyncClientService - XML deserialized!");
if (OnReceivedIndex != null)
OnReceivedIndex(null);
break;
case RequestTypes.GetPlayerStatus:
break;
case RequestTypes.GetPlaylist:
break;
case RequestTypes.Remote:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void HandleDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled) return;
_stopwatch.Stop();
if (e.Error != null)
{
Console.WriteLine("SyncClientService - HandleDownloadFileCompleted - Error: {0}", e.Error);
_errorCount++;
}
else
{
// TODO: Check if the ID is already in the database! If yes, that means the insert statement will fail.
Console.WriteLine("SyncClientService - HandleDownloadFileCompleted - File downloaded; inserting audio file into database...");
var audioFile = _audioFiles[_filesDownloaded];
string localFilePath = GetLibraryLocalPath(audioFile);
audioFile.FilePath = localFilePath;
_libraryService.InsertAudioFile(audioFile);
}
_filesDownloaded++;
var entity = new SyncClientDownloadAudioFileProgressEntity() {
Status = "Downloading files...",
PercentageDone = ((float)_filesDownloaded / (float)_audioFiles.Count()) * 100f,
FilesDownloaded = _filesDownloaded,
TotalFiles = _audioFiles.Count(),
DownloadSpeed = GetDownloadSpeed(),
Errors = _errorCount,
Log = string.Empty
};
// Download the next file
if(_filesDownloaded < _audioFiles.Count)
{
Console.WriteLine("SyncClientService - HandleDownloadFileCompleted - Downloading next file {0}...", _audioFiles[_filesDownloaded].FilePath);
if (OnDownloadAudioFileCompleted != null) OnDownloadAudioFileCompleted(entity);
DownloadAudioFile(_audioFiles[_filesDownloaded]);
return;
}
// Process is over; refresh cache
Console.WriteLine("SyncClientService - HandleDownloadFileCompleted - Process is over, refreshing audio file cache...");
entity.Status = "Refreshing cache...";
if (OnDownloadAudioFileCompleted != null) OnDownloadAudioFileCompleted(entity);
_audioFileCacheService.RefreshCache();
if (OnDownloadAudioFilesCompleted != null)
OnDownloadAudioFilesCompleted(this, new EventArgs());
}
public void Cancel()
{
Console.WriteLine("SyncClientService - Cancelling...");
if (_webClient.IsBusy)
_webClient.CancelAsync();
}
public void DownloadIndex(SyncDevice device)
{
if (string.IsNullOrEmpty(device.Url))
return;
var url = new Uri(new Uri(device.Url), "/api/index/xml");
Cancel();
Console.WriteLine("SyncClientService - Downloading index from {0}...", url);
_webClient.DownloadStringAsync(url, RequestTypes.DownloadIndex);
}
public void GetEQPresets(SyncDevice device)
{
if (string.IsNullOrEmpty(device.Url))
return;
var url = new Uri(new Uri(device.Url), "/api/eqpresets");
Cancel();
Console.WriteLine("SyncClientService - Downloading EQ presets from {0}...", url);
_webClient.DownloadStringAsync(url, RequestTypes.GetEQPresets);
}
public void GetMarkers(SyncDevice device, Guid audioFileId)
{
if (string.IsNullOrEmpty(device.Url))
return;
var url = new Uri(new Uri(device.Url), string.Format("/api/markers/{0}", audioFileId));
Cancel();
Console.WriteLine("SyncClientService - Downloading markers from {0} (audioFileId: {1})...", url, audioFileId);
_webClient.DownloadStringAsync(url, RequestTypes.GetMarkers);
}
public void GetLoops(SyncDevice device, Guid audioFileId)
{
if (string.IsNullOrEmpty(device.Url))
return;
var url = new Uri(new Uri(device.Url), string.Format("/api/loops/{0}", audioFileId));
Cancel();
Console.WriteLine("SyncClientService - Downloading loops from {0} (audioFileId: {1})...", url, audioFileId);
_webClient.DownloadStringAsync(url, RequestTypes.GetLoops);
}
public void GetPlayerStatus(string deviceUrl)
{
var url = new Uri(new Uri(deviceUrl), "/api/player");
Cancel();
Console.WriteLine("SyncClientService - Downloading index from {0}...", url);
_webClient.DownloadStringAsync(url, RequestTypes.GetPlayerStatus);
}
public List<string> GetDistinctArtistNames()
{
return _audioFiles.Select(x => x.ArtistName).Distinct().ToList();
}
public List<string> GetDistinctAlbumTitles(string artistName)
{
return _audioFiles.Where(x => x.ArtistName.ToUpper() == artistName.ToUpper()).Select(x => x.AlbumTitle).Distinct().ToList();
}
public List<AudioFile> GetAudioFiles()
{
return _audioFiles;
}
public List<AudioFile> GetAudioFiles(string artistName)
{
return _audioFiles.Where(x => x.ArtistName.ToUpper() == artistName.ToUpper()).ToList();
}
public List<AudioFile> GetAudioFiles(string artistName, string albumTitle)
{
return _audioFiles.Where(x => x.ArtistName.ToUpper() == artistName.ToUpper() && x.AlbumTitle.ToUpper() == albumTitle.ToUpper()).ToList();
}
public void DownloadAudioFiles(SyncDevice device, IEnumerable<AudioFile> audioFiles)
{
if (_webClient.IsBusy)
return;
_filesDownloaded = 0;
_bytesDownloaded = 0;
_errorCount = 0;
CurrentDevice = device;
_audioFiles = audioFiles.ToList();
if (OnDownloadAudioFileProgress != null)
OnDownloadAudioFileProgress(new SyncClientDownloadAudioFileProgressEntity(){
Status = "Downloading files...",
PercentageDone = 0,
FilesDownloaded = 0,
TotalFiles = _audioFiles.Count(),
DownloadSpeed = GetDownloadSpeed(),
Errors = _errorCount,
Log = string.Empty
});
var audioFile = _audioFiles[0];
_stopwatch.Reset();
DownloadAudioFile(audioFile);
}
private void DownloadAudioFile(AudioFile audioFile)
{
var url = new Uri(new Uri(CurrentDevice.Url), string.Format("/api/audiofile/{0}", audioFile.Id.ToString()));
string localFilePath = GetLibraryLocalPath(audioFile);
//Console.WriteLine("SyncClientService - DownloadAudioFile - folderPath: {0} fileName: {1} localFilePath: {2}", folderPath, fileName, localFilePath);
_lastBytesReceived = 0;
if (OnDownloadAudioFileStarted != null)
OnDownloadAudioFileStarted(new SyncClientDownloadAudioFileProgressEntity(){
Status = "Downloading files...",
PercentageDone = ((float)_filesDownloaded / (float)_audioFiles.Count()) * 100f,
FilesDownloaded = _filesDownloaded,
DownloadFileName = Path.GetFileName(audioFile.FilePath),
TotalFiles = _audioFiles.Count(),
DownloadSpeed = GetDownloadSpeed(),
Errors = _errorCount,
Log = string.Empty
});
_stopwatch.Start();
_webClient.DownloadFileAsync(url, localFilePath);
}
private string GetLibraryLocalPath(AudioFile audioFile)
{
string fileName = Path.GetFileName(audioFile.FilePath);
string folderPath = _deviceSpecifications.GetMusicFolderPath();
// Add artist name to the path (create folder if necessary)
folderPath = Path.Combine(folderPath, audioFile.ArtistName);
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
// Add album title to the path (create folder if necessary)
folderPath = Path.Combine(folderPath, audioFile.AlbumTitle);
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
return Path.Combine(folderPath, fileName);
}
public enum RequestTypes
{
DownloadIndex = 0,
GetPlayerStatus = 1,
GetPlaylist = 2,
GetEQPresets = 3,
GetMarkers = 4,
GetLoops = 5,
Remote = 6
}
}
}