-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
352 lines (302 loc) · 15.7 KB
/
MainForm.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
using GanjoorTranslationTagger.ImportedViewModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RMuseum.Models.Ganjoor;
using RMuseum.Models.Ganjoor.ViewModels;
using RMuseum.Services.Implementation.ImportedFromDesktopGanjoor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Windows.Forms;
namespace GanjoorTranslationTagger
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
txtEmail.Text = Properties.Settings.Default.Email;
if (!string.IsNullOrEmpty(Properties.Settings.Default.MuseumToken))
lblLoginStatus.Text = "شما وارد سیستم شدهاید!";
}
private async void MainForm_Load(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
Application.DoEvents();
using (HttpClient httpClient = new HttpClient())
{
var languagesApiUrl = "https://api.ganjoor.net/api/translations/languages";
var response = await httpClient.GetAsync(languagesApiUrl);
if (response.StatusCode != HttpStatusCode.OK)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await response.Content.ReadAsStringAsync());
return;
}
response.EnsureSuccessStatusCode();
cmbLanguage.DataSource = JArray.Parse(await response.Content.ReadAsStringAsync()).ToObject<List<GanjoorLanguage>>();
cmbLanguage.SelectedIndex = cmbLanguage.Items.Count - 1;
}
Cursor = Cursors.Default;
}
private async void btnLogin_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
Enabled = false;
Application.DoEvents();
DialogResult = DialogResult.None;
LoginViewModel model = new LoginViewModel()
{
Username = txtEmail.Text,
Password = txtPassword.Text,
ClientAppName = "Ganjoor Translation Tagger",
Language = "fa-IR"
};
using (HttpClient httpClient = new HttpClient())
{
var stringContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var loginUrl = "https://api.ganjoor.net/api/users/login";
var response = await httpClient.PostAsync(loginUrl, stringContent);
if (response.StatusCode != HttpStatusCode.OK)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await response.Content.ReadAsStringAsync());
return;
}
response.EnsureSuccessStatusCode();
var result = JObject.Parse(await response.Content.ReadAsStringAsync());
Properties.Settings.Default.Email = txtEmail.Text;
Properties.Settings.Default.MuseumToken = result["token"].ToString();
Properties.Settings.Default.SessionId = Guid.Parse(result["sessionId"].ToString());
Properties.Settings.Default.UserId = Guid.Parse(result["user"]["id"].ToString());
Properties.Settings.Default.Save();
}
Enabled = true;
Cursor = Cursors.Default;
DialogResult = DialogResult.OK;
}
private void btnLanguages_Click(object sender, EventArgs e)
{
Process.Start("https://ganjoor.net/User/Languages");
}
private void btnSelectCategory_Click(object sender, EventArgs e)
{
using(SelectPoet poetsDialog = new SelectPoet())
{
if(poetsDialog.ShowDialog(this) == DialogResult.OK)
{
using(SelectCategory dlg = new SelectCategory(poetsDialog.SelectedPoet))
if(dlg.ShowDialog(this) == DialogResult.OK)
{
_selectedCat = dlg.SelectedCat;
lblSelectedCat.Text = _selectedCat.ToString();
}
}
}
}
private GanjoorCatViewModel _selectedCat = null;
private async void btnStartTranslating_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Properties.Settings.Default.MuseumToken))
{
MessageBox.Show("لطفاً وارد سیستم شوید.");
return;
}
if (_selectedCat == null)
{
MessageBox.Show("لطفاً بخش مد نظر را انتخاب کنید.");
return;
}
if(cmbLanguage.SelectedItem == null)
{
MessageBox.Show("لطفاً زبان مد نظر را انتخاب کنید.");
return;
}
var language = cmbLanguage.SelectedItem as GanjoorLanguage;
if (MessageBox.Show($"آیا از برگردان {_selectedCat} به {cmbLanguage.SelectedItem} اطمینان دارید؟", "تأییدیه", MessageBoxButtons.YesNo) == DialogResult.No)
{
return;
}
Cursor = Cursors.WaitCursor;
Application.DoEvents();
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Properties.Settings.Default.MuseumToken);
var catsApiUrl = $"https://api.ganjoor.net/api/ganjoor/cat/{_selectedCat.Id}?poems=true";
var response = await httpClient.GetAsync(catsApiUrl);
if (response.StatusCode != HttpStatusCode.OK)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await response.Content.ReadAsStringAsync());
return;
}
response.EnsureSuccessStatusCode();
var catWithListOfPoems = JObject.Parse(await response.Content.ReadAsStringAsync()).ToObject<GanjoorPoetCompleteViewModel>();
foreach(var poem in catWithListOfPoems.Cat.Poems)
{
var responsePoem = await httpClient.GetAsync($"https://api.ganjoor.net/api/ganjoor/poem/{poem.Id}?verseDetails=true&catInfo=true&rhymes=false&recitations=false&images=false&songs=false&comments=false&navigation=true");
if (!responsePoem.IsSuccessStatusCode)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await response.Content.ReadAsStringAsync());
return;
}
responsePoem.EnsureSuccessStatusCode();
var poemWithVerses = JsonConvert.DeserializeObject<GanjoorPoemCompleteViewModel>(await responsePoem.Content.ReadAsStringAsync());
List<GanjoorVerseTranslationViewModel> verses = new List<GanjoorVerseTranslationViewModel>();
foreach (GanjoorVerseViewModel v in poemWithVerses.Verses)
{
verses.Add
(
new GanjoorVerseTranslationViewModel()
{
Verse = new GanjoorVerseViewModel() { VOrder = v.VOrder },
TText = GPersianTextSync.Farglisize(v.Text)
}
);
}
var translation = new GanjoorPoemTranslationViewModel()
{
Language = language,
PoemId = poemWithVerses.Id,
Title = GPersianTextSync.Farglisize(poemWithVerses.Title),
Published = false,
Description = "برچسبگذاری خودکار توسط برنامهٔ آزمایشی",
TranslatedVerses = verses.ToArray()
};
HttpResponseMessage responseTranslation = await httpClient.PostAsync($"https://api.ganjoor.net/api/translations",
new StringContent(JsonConvert.SerializeObject(translation),
Encoding.UTF8,
"application/json"));
if (!responseTranslation.IsSuccessStatusCode)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await responseTranslation.Content.ReadAsStringAsync());
return;
}
}
}
Cursor = Cursors.Default;
MessageBox.Show("انجام شد.");
}
private async void btnBackup_Click(object sender, EventArgs e)
{
using(FolderBrowserDialog dlg = new FolderBrowserDialog())
{
if(dlg.ShowDialog() == DialogResult.OK)
{
string dir = dlg.SelectedPath;
string jsonDir = Path.Combine(dir, "json");
if(!Directory.Exists(jsonDir))
{
Directory.CreateDirectory(jsonDir);
}
Cursor = Cursors.WaitCursor;
Application.DoEvents();
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Properties.Settings.Default.MuseumToken);
int pageNumber = 1;
int totalCount = 1;
Enabled = false;
do
{
var translationsUrl = $"https://api.ganjoor.net/api/translations/all/{(cmbLanguage.SelectedItem as GanjoorLanguage).Id}?PageNumber={pageNumber}&PageSize=1000";
var responseTranslations = await httpClient.GetAsync(translationsUrl);
if (responseTranslations.StatusCode != HttpStatusCode.OK)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await responseTranslations.Content.ReadAsStringAsync());
return;
}
responseTranslations.EnsureSuccessStatusCode();
var translations = JArray.Parse(await responseTranslations.Content.ReadAsStringAsync()).ToObject<List<GanjoorPoemTranslationViewModel>>();
if(translations.Count == 0)
{
break;
}
string paginationMetadataJsonValue = responseTranslations.Headers.GetValues("paging-headers").FirstOrDefault();
if(totalCount == 1)
{
if (!string.IsNullOrEmpty(paginationMetadataJsonValue))
{
var meta = JsonConvert.DeserializeObject<PaginationMetadata>(paginationMetadataJsonValue);
totalCount = meta.totalCount;
prgrss.Value = 0;
prgrss.Maximum = totalCount;
}
}
foreach (var translation in translations)
{
prgrss.Value++;
Application.DoEvents();
var translationUrl = $"https://api.ganjoor.net/api/translations/{translation.Id}";
var response = await httpClient.GetAsync(translationUrl);
if (response.StatusCode != HttpStatusCode.OK)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await response.Content.ReadAsStringAsync());
return;
}
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var translationCompleteViewModel = JsonConvert.DeserializeObject<GanjoorPoemTranslationViewModel>(json);
File.WriteAllText(Path.Combine(jsonDir, translationCompleteViewModel.PoemId.ToString() + ".json"), json);
var responsePoem = await httpClient.GetAsync($"https://api.ganjoor.net/api/ganjoor/poem/{translationCompleteViewModel.PoemId}?verseDetails=true&catInfo=true&rhymes=false&recitations=false&images=false&songs=false&comments=false&navigation=true");
if (!responsePoem.IsSuccessStatusCode)
{
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show(await response.Content.ReadAsStringAsync());
return;
}
responsePoem.EnsureSuccessStatusCode();
var poemWithVerses = JsonConvert.DeserializeObject<GanjoorPoemCompleteViewModel>(await responsePoem.Content.ReadAsStringAsync());
string catDir = dir;
foreach(var cat in poemWithVerses.Category.Cat.Ancestors)
{
catDir = Path.Combine(catDir, cat.Title);
if(!Directory.Exists(catDir))
{
Directory.CreateDirectory(catDir);
}
}
catDir = Path.Combine(catDir, poemWithVerses.Category.Cat.Title);
if(!Directory.Exists(catDir))
{
Directory.CreateDirectory(catDir);
}
List<string> list = new List<string>();
foreach(var v in translationCompleteViewModel.TranslatedVerses)
{
list.Add(v.Verse.Text);
list.Add(v.TText);
}
File.WriteAllLines(Path.Combine(catDir, poemWithVerses.Title + ".txt"), list.ToArray());
}
pageNumber++;
}
while (true);
}
Cursor = Cursors.Default;
Enabled = true;
MessageBox.Show("انجام شد.");
}
}
}
}
}