Skip to content

Commit d410a1f

Browse files
committed
lots update
1 parent 0b022fe commit d410a1f

File tree

8 files changed

+206
-77
lines changed

8 files changed

+206
-77
lines changed

DesktopClient/Helpers/EncodingDetector.cs

Lines changed: 138 additions & 12 deletions
Large diffs are not rendered by default.

DesktopClient/Main.Designer.cs

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

DesktopClient/Main.cs

Lines changed: 46 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using SubDBSharp.Http;
55
using System;
66
using System.Collections.Generic;
7+
using System.Diagnostics;
78
using System.IO;
89
using System.Linq;
910
using System.Text;
@@ -18,7 +19,7 @@ public partial class Main : Form
1819
private string _rootDirectory;
1920

2021
// Contains list of movie/tv-show to be downloaded
21-
private IList<MediaInfo> _mediaFiles;
22+
private readonly IList<MediaInfo> _mediaFiles;
2223

2324
// SubDbSharp api client
2425
private readonly SubDBClient _client;
@@ -34,12 +35,11 @@ public Main()
3435

3536
IgnoreExtensions = new HashSet<string>()
3637
{
37-
".srt", ".txt", ".nfo", ".mp3", ".jpg", ".rar", ".zip", ".7zip"
38+
".srt", ".txt", ".nfo", ".mp3", ".jpg", ".rar", ".zip", ".7zip", ".png"
3839
};
3940

4041
_mediaFiles = new List<MediaInfo>();
4142

42-
4343
// initialize encoding combobox
4444
InitializeEncoding();
4545

@@ -50,17 +50,16 @@ public Main()
5050
private void InitializeLanguageCombobox()
5151
{
5252
// .Result can produce a deadlock in certain scenario's
53-
Response languages = _client.GetAvailableLanguagesAsync().Result;
53+
Response languages = _client.GetAvailableLanguagesAsync().GetAwaiter().GetResult();
5454

5555
byte[] buffer = (byte[])languages.Body;
5656
string csvLanguage = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
5757

5858
// e.g: en, pt, fr...
5959
foreach (string language in csvLanguage.Split(','))
6060
{
61-
var cbi = new LanguageItem(language);
62-
// TODO: Review why after .ToString() return EnglishName (e.g: English) it keeps
63-
// showing "en" instead...
61+
LanguageItem cbi = new LanguageItem(language);
62+
// TODO: Review why after .ToString() return EnglishName (e.g: English) it keeps showing "en" instead...
6463
comboBoxLanguage.Items.Add(cbi);
6564
}
6665

@@ -73,7 +72,7 @@ private void InitializeEncoding()
7372
int utf8Idx = -1;
7473
foreach (EncodingInfo encoding in Encoding.GetEncodings())
7574
{
76-
var ei = new EncodingItem
75+
EncodingItem ei = new EncodingItem
7776
{
7877
Encoding = encoding.GetEncoding()
7978
};
@@ -91,14 +90,12 @@ private void InitializeEncoding()
9190

9291
private void ButtonBrowse_Click(object sender, EventArgs e)
9392
{
94-
using (var fbd = new FolderBrowserDialog())
93+
using (FolderBrowserDialog folderDialog = new FolderBrowserDialog { ShowNewFolderButton = true, SelectedPath = _rootDirectory })
9594
{
96-
// Configure folder dialog
97-
98-
if (fbd.ShowDialog() == DialogResult.OK)
95+
if (folderDialog.ShowDialog() == DialogResult.OK)
9996
{
100-
textBoxPath.Text = fbd.SelectedPath;
101-
// get all movie files and store them in a list for later access...
97+
_rootDirectory = folderDialog.SelectedPath;
98+
textBoxPath.Text = folderDialog.SelectedPath;
10299
}
103100
}
104101
}
@@ -108,19 +105,20 @@ private int LoadMedias()
108105
_mediaFiles.Clear();
109106
foreach (string file in Directory.GetFiles(_rootDirectory))
110107
{
111-
if (IgnoreExtensions.Contains(Path.GetExtension(file)))
108+
// filter extension
109+
string lowerExtension = Path.GetExtension(file);
110+
if (IgnoreExtensions.Contains(lowerExtension))
112111
{
113112
continue;
114113
}
115-
var mf = new MediaInfo(file);
116-
_mediaFiles.Add(mf);
114+
115+
_mediaFiles.Add(MediaInfo.FromFile(file));
117116
}
118117
return _mediaFiles.Count;
119118
}
120119

121120
private async void ButtonDownload_Click(object sender, EventArgs e)
122121
{
123-
124122
// validation fails
125123
if (!IsValid())
126124
{
@@ -134,54 +132,67 @@ private async void ButtonDownload_Click(object sender, EventArgs e)
134132
//disable all controls
135133
ChangeControlsState(false);
136134

137-
await DownloadAsync();
135+
await DownloadAsync().ConfigureAwait(true);
138136

139-
//await Task.Yield(); was an attemp to continue on main thread
137+
// force async
138+
//await Task.Yield();
140139
//ChangeControlsStates(false);
141-
142140
}
143141

144142
private async Task DownloadAsync()
145143
{
146-
var cbi = (LanguageItem)comboBoxLanguage.SelectedItem;
144+
LanguageItem cbi = (LanguageItem)comboBoxLanguage.SelectedItem;
147145

148146
// encoding used to write content in file
149147
Encoding writeEncoding = ((EncodingItem)comboBoxEncoding.SelectedItem).Encoding;
150148

151-
// REPORT DOWNLOAD PROGRESS
152-
var progressHandler = new Progress<int>(value =>
149+
// report download progress
150+
Progress<string> progressReporter = new Progress<string>(value =>
153151
{
154-
progressBar1.Value += value;
152+
//progressBar1.Value += value;
153+
progressBar1.Value += 1;
154+
if (File.Exists(value))
155+
{
156+
Trace.WriteLine("file downloaded!");
157+
}
155158
if (progressBar1.Value == progressBar1.Maximum)
156159
{
157160
MessageBox.Show("Download completed!");
158161
ChangeControlsState(true);
159162
}
160163
});
161164

162-
var progress = progressHandler as IProgress<int>;
165+
// this need to happen because Progress<T> implement IProgress interface explicitly
166+
IProgress<string> reporter = progressReporter;
163167

164168
for (int i = 0; i < _mediaFiles.Count; ++i)
165169
{
166170
MediaInfo mediaInfo = _mediaFiles[i];
167-
Response response = await _client.DownloadSubtitleAsync(mediaInfo.Hash, cbi.CultureInfo.TwoLetterISOLanguageName).ConfigureAwait(false);
168171

169-
// report progress
170-
progress?.Report(1);
172+
Response response = await _client.DownloadSubtitleAsync(mediaInfo.Hash,
173+
cbi.CultureInfo.TwoLetterISOLanguageName).ConfigureAwait(false);
171174

175+
// download failed
172176
if (response.StatusCode != System.Net.HttpStatusCode.OK)
173177
{
178+
Trace.WriteLine($"Failed downloadeding: {_mediaFiles[i].FileInfo.Name}");
174179
continue;
175180
}
176-
string path = Path.Combine(Path.GetDirectoryName(mediaInfo.FileInfo.FullName), Path.GetFileNameWithoutExtension(mediaInfo.FileInfo.Name) + ".srt");
181+
182+
// generate file output location
183+
string path = Path.Combine(Path.GetDirectoryName(mediaInfo.FileInfo.FullName),
184+
Path.GetFileNameWithoutExtension(mediaInfo.FileInfo.Name) + ".srt");
177185

178186
byte[] buffer = (byte[])response.Body;
179187

180-
// encoding used to read data
181-
Encoding readEncoding = EncodingDetector.DetectAnsiEncoding(buffer);
188+
// read content using guessed encoding
189+
string content = EncodingDetector.DetectAnsiEncoding(buffer).GetString(buffer, 0, buffer.Length);
182190

183-
string content = readEncoding.GetString(buffer, 0, buffer.Length);
191+
// write downloaded file to disk
184192
File.WriteAllText(path, content, writeEncoding);
193+
194+
// report progress
195+
reporter?.Report(path);
185196
}
186197
}
187198

@@ -197,7 +208,6 @@ private void ChangeControlsState(bool enabled)
197208

198209
private bool IsValid()
199210
{
200-
_rootDirectory = textBoxPath.Text.Trim();
201211
if (!Path.IsPathRooted(_rootDirectory))
202212
{
203213
MessageBox.Show("Invalid path!");
@@ -217,7 +227,7 @@ private bool IsValid()
217227
return true;
218228
}
219229

220-
private void textBox1_DragEnter(object sender, DragEventArgs e)
230+
private void TextBox1_DragEnter(object sender, DragEventArgs e)
221231
{
222232
e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None;
223233
}
@@ -231,4 +241,5 @@ private void textBox1_DragDrop(object sender, DragEventArgs e)
231241
}
232242
}
233243
}
244+
234245
}

DesktopClient/Models/MediaInfo.cs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,17 @@ namespace DesktopClient.Models
44
{
55
public class MediaInfo
66
{
7-
public string Hash { get; }
8-
public FileInfo FileInfo { get; }
7+
public string Hash { get; private set; }
8+
public FileInfo FileInfo { get; private set; }
99

10-
public MediaInfo(string file)
10+
public static MediaInfo FromFile(string file)
1111
{
12-
Hash = SubDBSharp.Helpers.Utils.GetMovieHash(file);
13-
FileInfo = new FileInfo(file);
12+
return new MediaInfo
13+
{
14+
Hash = SubDBSharp.Helpers.Utils.GetMovieHash(file),
15+
FileInfo = new FileInfo(file),
16+
};
1417
}
18+
1519
}
1620
}

UnitTest/SubDBClient.Test.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ public async Task TestAvailableLanguages()
2424
Assert.True(availableLanguages.Count > 0);
2525
}
2626

27-
/*
2827
[Fact]
2928
public async Task TestSearchSubtitle()
3029
{
@@ -37,7 +36,6 @@ public async Task TestSearchSubtitle()
3736
var availableLanguages = ReponseParser.ParseGetAvailablesLanguages(body);
3837
Assert.True(availableLanguages.Count > 0);
3938
}
40-
*/
4139

4240
[Fact]
4341
public async Task TestDownloadSubtitle()

src/Http/Request.cs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,8 @@ namespace SubDBSharp.Models
55
{
66
public class Request : IRequest
77
{
8-
public Request(Uri endpoint, HttpMethod method, HttpContent content)
9-
{
10-
EndPoint = endpoint;
11-
Method = method;
12-
Body = content;
13-
}
14-
15-
public Uri EndPoint { get; }
16-
public HttpMethod Method { get; }
17-
public HttpContent Body { get; }
8+
public Uri EndPoint { get; set; }
9+
public HttpMethod Method { get; set; }
10+
public HttpContent Body { get; set; }
1811
}
1912
}

src/Http/SubDBApi.cs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public Task<Response> SearchSubtitle(string hash, bool getVersions = false)
6767
return SendDataAsync(request);
6868
#else
6969
// NOTE: THIS CODE IS ONLY FOR TEST. (SUBDB DOESN'T ENCODED QUERY STRING)
70-
// ONCE THE QUERY STRING IS ENCODED IT'S PUT INSIDE HTTP BODY ISNTEAD OF URL
70+
// ONCE THE QUERY STRING IS ENCODED IT'S PUT INSIDE HTTP BODY INSTEAD OF URL
7171
Dictionary<string, string> requestParameters = new Dictionary<string, string>
7272
{
7373
["action"] = "download",
@@ -142,15 +142,20 @@ protected virtual async Task<Response> BuildResponse(HttpResponseMessage respons
142142
object responseBody;
143143
using (HttpContent content = responseMessage.Content)
144144
{
145-
// get can be more processing like getting the metia type before reading
145+
// get can be more processing like getting the media type before reading
146146
// the content information, but subdb always return string
147147
responseBody = await content?.ReadAsByteArrayAsync();
148148
}
149149
return new Response(responseMessage.StatusCode, responseBody,
150150
responseMessage.Headers.ToDictionary(h => h.Key, h => h.Value.First()));
151151
}
152152

153-
protected virtual Request BuildRequest(Uri endPoint, HttpMethod method, HttpContent body) => new Request(endPoint, method, body);
153+
protected virtual Request BuildRequest(Uri endPoint, HttpMethod method, HttpContent body) => new Request
154+
{
155+
EndPoint = endPoint,
156+
Body = body,
157+
Method = method,
158+
};
154159

155160
private static HttpContent BuildFormContent(string subtitle, string movie)
156161
{
@@ -180,10 +185,6 @@ private static HttpContent BuildFormContent(string subtitle, string movie)
180185
return content;
181186
}
182187

183-
public void Dispose()
184-
{
185-
// calling dispose in _httClient handler will also dispose _httpClientHandler. (set in contructor)
186-
_httpClient.Dispose();
187-
}
188+
public void Dispose() => _httpClient.Dispose(); // calling dispose in _httClient handler will also dispose _httpClientHandler. (set in contructor)
188189
}
189190
}

src/SubDBClient.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@ public class SubDBClient : IDisposable, ISubDBClient
1111
private readonly SubDBApi _subDbApi;
1212
private readonly IResponseParser _responseParser;
1313

14-
#region Constuctors
15-
1614
public SubDBClient(ProductHeaderValue productInformation)
1715
: this(productInformation, ApiUrls.SubDBApiUrl)
1816
{
@@ -25,8 +23,6 @@ public SubDBClient(ProductHeaderValue productInformation, Uri baseAddress)
2523
_responseParser = new CsvResponseParser();
2624
}
2725

28-
#endregion
29-
3026
/// <summary>
3127
/// Lists the languages of all subtitles currenttly available in database.
3228
/// </summary>

0 commit comments

Comments
 (0)