-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1459 lines (1347 loc) · 62 KB
/
MainWindow.xaml.cs
File metadata and controls
1459 lines (1347 loc) · 62 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
using System.Windows.Input;
using System.Web;
using System.Collections.Specialized;
using System.Diagnostics;
using Libs;
using Web;
using MimeKit;
using MailKit.Net.Smtp;
using Newtonsoft.Json;
using Org.BouncyCastle.Utilities.Collections;
namespace JobCatcher
{
public partial class MainWindow : Window
{
Properties.Settings config = Properties.Settings.Default;
List<Profile> prs = new List<Profile>();
bool stop = false;
DispatcherTimer timerWork = new DispatcherTimer();
DispatcherTimer timerFl = new DispatcherTimer();
DispatcherTimer timerUpdateResume = new DispatcherTimer();
Task taskWork;
Task taskFl;
Task taskUpdateResume;
List<Vacancy> flVacancies = new List<Vacancy>();
List<Vacancy> workVacancies = new List<Vacancy>();
string xcsrftoken = "";
Stopwatch sw;
public MainWindow()
{
InitializeComponent();
}
#region Иконка в трее
private System.Windows.Forms.NotifyIcon trayIcon = null;
private System.Windows.Controls.ContextMenu trayMenu = null;
private WindowState fCurrentWindowState = WindowState.Normal;
public WindowState CurrentWindowState
{
get { return fCurrentWindowState; }
set { fCurrentWindowState = value; }
}
private bool fCanClose = false;
public bool CanClose
{
get { return fCanClose; }
set { fCanClose = value; }
}
/// <summary>
/// Переопределяет обработку первичной инициализации приложения
/// </summary>
/// <param name="e"></param>
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
CreateTrayIcon();
}
/// <summary>
/// Создание иконки
/// </summary>
/// <returns></returns>
private bool CreateTrayIcon()
{
bool result = false;
if (trayIcon == null)
{
trayIcon = new System.Windows.Forms.NotifyIcon();
trayIcon.Icon = JobCatcher.Properties.Resources.icon;
trayIcon.Text = this.Title;
trayMenu = Resources["trayMenu"] as System.Windows.Controls.ContextMenu;
//Поведение иконки при щелчке мыши
trayIcon.Click += delegate(object sender, EventArgs e)
{
if ((e as System.Windows.Forms.MouseEventArgs).Button == System.Windows.Forms.MouseButtons.Left)
{
ShowHideMainWindow(sender, null);
}
else
{
trayMenu.IsOpen = true;
Activate();
}
};
result = true;
}
else
{
result = true;
}
trayIcon.Visible = true;
return result;
}
/// <summary>
/// Показывает или скрывает главное окно
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ShowHideMainWindow(object sender, RoutedEventArgs e)
{
trayMenu.IsOpen = false;
if (IsVisible)
{
Hide();
(trayMenu.Items[0] as System.Windows.Controls.MenuItem).Header = "Показать";
}
else
{
Show();
(trayMenu.Items[0] as System.Windows.Controls.MenuItem).Header = "Скрыть";
WindowState = CurrentWindowState;
Activate();
}
}
/// <summary>
/// Переопределяет встроенную реакцию на изменение состояния окна
/// </summary>
/// <param name="e"></param>
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
if (this.WindowState == System.Windows.WindowState.Minimized && config.minimTray)
{
//Сворачиваем в трей, если окно свернуто и выбрана галочка
Hide();
(trayMenu.Items[0] as System.Windows.Controls.MenuItem).Header = "Показать";
}
else
{
CurrentWindowState = WindowState;
}
}
/// <summary>
/// Переопределяет обработчик запроса выхода из приложения
/// </summary>
/// <param name="e"></param>
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
if (!CanClose)
{
e.Cancel = true;
CurrentWindowState = this.WindowState;
(trayMenu.Items[0] as System.Windows.Controls.MenuItem).Header = "Показать";
Hide();
}
else
{
trayIcon.Visible = false;
}
}
/// <summary>
/// Меню Выход
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MenuExitClick(object sender, RoutedEventArgs e)
{
CanClose = true;
this.Close();
}
#endregion
#region Отображение окон
public void ShowSettings()
{
Window window = new Settings();
window.Owner = this;
Settings windowObject = window as Settings;
window.ShowDialog();
}
public void ShowPopup(Vacancy v)
{
Dispatcher.BeginInvoke(new Action(() =>
{
Window window = new PopupWindow();
PopupWindow windowObject = window as PopupWindow;
windowObject.Title = v.Name;
windowObject.profileName.Text = v.ProfileName;
windowObject.date.Text = v.Date + ", ";
windowObject.city.Text = v.City + (!string.IsNullOrEmpty(v.Company) ? ", " : "");
windowObject.company.Text = v.Company;
windowObject.salary.Text = v.Salary + (!string.IsNullOrEmpty(v.Salary) ? ", " : "");
windowObject.panel.ToolTip = string.Format("{0}, {1}, {2}, {3}", v.Date, v.City, v.Company, v.Salary);
windowObject.employmentType.Text = v.Content;
windowObject.detail.Tag = v.Id;
windowObject.answer.Tag = v.Id;
windowObject.main = this;
JobHelper.popupWindows.Add(window);
double factor = System.Windows.PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11;
int resX = (int)(System.Windows.Forms.Screen.GetWorkingArea(new System.Drawing.Point()).Width / factor);
int resY = (int)(System.Windows.Forms.Screen.GetWorkingArea(new System.Drawing.Point()).Height / factor);
int multipX = (int)(resX / windowObject.Width);
int multipY = (int)(resY / windowObject.Height);
int x = JobHelper.popupWindows.Count / multipY + 1;
int y = JobHelper.popupWindows.Count % multipY;
if (y == 0) { y = multipY; x--; }
int left = resX - (int)windowObject.Width * x;
int top = resY - (int)windowObject.Height * y;
if (left > 0)
{
windowObject.Left = left;
windowObject.Top = top;
windowObject.ShowActivated = false;
window.Show();
}
else JobHelper.popupWindows.Remove(window);
}));
}
public void ShowDetail(Vacancy v)
{
Window window = new DetailWindow();
window.Owner = this;
DetailWindow windowObject = window as DetailWindow;
windowObject.Title = v.Name;
windowObject.content = v.Content;
windowObject.answer.Tag = v.Id;
window.ShowDialog();
}
#endregion
#region События окна
private void Window_Loaded(object sender, RoutedEventArgs e)
{
CanClose = !config.closeTray;
timerWork.Tick += new EventHandler(timerWork_Tick);
timerFl.Tick += new EventHandler(timerFl_Tick);
timerUpdateResume.Tick += new EventHandler(timerUpdateResume_Tick);
LoadConfig();
playButton_Click(this, null);
}
void Window_Closing(object sender, EventArgs e)
{
removeWindows_Click(this, null);
config.Save();
}
#endregion
#region Таймеры
void timerWork_Tick(object sender, EventArgs e)
{
if (taskWork.Status != TaskStatus.Running) { taskWork = new Task(() => StartWork()); taskWork.Start(); }
}
void timerFl_Tick(object sender, EventArgs e)
{
if (taskFl.Status != TaskStatus.Running) { taskFl = new Task(() => StartFl()); taskFl.Start(); }
}
void timerUpdateResume_Tick(object sender, EventArgs e)
{
if (taskUpdateResume.Status != TaskStatus.Running) { taskUpdateResume = new Task(() => StartUpdateResume()); taskUpdateResume.Start(); }
}
#endregion
#region Панель инструментов
private void playButton_Click(object sender, RoutedEventArgs e)
{
if (!SaveConfig()) return;
playButton.Visibility = System.Windows.Visibility.Collapsed;
pauseButton.Visibility = System.Windows.Visibility.Visible;
stop = false;
//taskWork = new Task(() => StartWork()); taskWork.Start();
//timerWork.Interval = TimeSpan.FromSeconds(config.periodWork); timerWork.Start();
taskFl = new Task(() => StartFl()); taskFl.Start();
timerFl.Interval = TimeSpan.FromSeconds(config.periodFl); timerFl.Start();
//taskUpdateResume = new Task(() => StartUpdateResume()); taskUpdateResume.Start();
//timerUpdateResume.Interval = TimeSpan.FromMinutes(config.periodUpdateResume); timerUpdateResume.Start();
Log("Запуск");
}
private void pauseButton_Click(object sender, RoutedEventArgs e)
{
playButton.Visibility = System.Windows.Visibility.Visible;
pauseButton.Visibility = System.Windows.Visibility.Collapsed;
stop = true;
timerWork.Stop();
Log("Остановлено");
}
private void exitButton_Click(object sender, RoutedEventArgs e)
{
CanClose = true;
this.Close();
}
private void settingsButton_Click(object sender, RoutedEventArgs e)
{
ShowSettings();
}
#endregion
#region События элементов
private void log_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Delete || e.Key == Key.Back)
{
log.Clear();
}
}
private void popup_Checked(object sender, RoutedEventArgs e)
{
config.popup = popup.IsChecked.Value;
config.Save();
}
private void workEnabled_Checked(object sender, RoutedEventArgs e)
{
config.workEnabled = workEnabled.IsChecked.Value;
config.Save();
}
private void flEnabled_Checked(object sender, RoutedEventArgs e)
{
config.flEnabled = flEnabled.IsChecked.Value;
config.Save();
}
private void returnButton_Click(object sender, RoutedEventArgs e)
{
var context = NewContext();
var set = context.Settings.First();
var v = context.Vacancies.FirstOrDefault(x => x.Id == set.LastVacancy);
v.Viewed = false;
context.SaveChanges();
flVacancies.Add(v);
RenderFlList();
}
#endregion
#region Work
private async void saveProfileWork_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(profileWorkCombo.Text)) { MessageBox.Show("Необходимо ввести название профиля", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; }
var context = NewContext();
var p = prs.FirstOrDefault(x => x.Name == profileWorkCombo.Text && x.Kind == "work");
if (p == null)
{
p = new Profile { Name = profileWorkCombo.Text, Kind = "work" };
prs.Add(p);
SaveConfig();
}
p.Search = searchWork.Text;
p.Answer = (bool)autoAnswerWork.IsChecked;
p.Salary = Helper.IntParse(salaryWork.Text);
p.Remote = (bool)remote.IsChecked;
p.Login = loginHh.Text;
p.Pass = passHh.Password;
p.ResumeLinkHh = resumeLinkHh.Text;
p.Proxy = proxyWork.Text;
SaveConfig();
RenderWorkCombo();
saveProfileWork.Content = "Сохранено";
await Task.Delay(5000);
saveProfileWork.Content = "Сохранить профиль";
}
private void profileWorkCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RenderWorkText();
RenderWorkList();
}
private void deleteProfileWork_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Удалить профиль?", "Вопрос", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
var context = NewContext();
var p = prs.FirstOrDefault(x => x.Name == profileWorkCombo.Text && x.Kind == "work");
if (p != null)
{
prs.Remove(p);
SaveConfig();
}
RenderWorkCombo(true);
}
}
private void workListGrid_MouseEnter(object sender, MouseEventArgs e)
{
var grid = sender as Grid;
grid.Style = (Style)FindResource("gridBackOver");
}
private void workListGrid_MouseLeave(object sender, MouseEventArgs e)
{
var grid = sender as Grid;
grid.Style = null;
}
public void detailWorkList_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var context = NewContext();
var v = context.Vacancies.FirstOrDefault(x => x.Id == (int)button.Tag);
v.Viewed = true;
var set = context.Settings.First();
set.LastVacancy = v.Id;
context.SaveChanges();
RenderWorkList();
}
private void allProfilesWork_Checked(object sender, RoutedEventArgs e)
{
RenderWorkList();
}
private void removeWindows_Click(object sender, RoutedEventArgs e)
{
try
{
var wins = JobHelper.popupWindows.ToList();
JobHelper.popupWindows.Clear();
foreach (var win in wins) win.Close();
}
catch { }
}
private void removeListWork_Click(object sender, RoutedEventArgs e)
{
var context = NewContext();
var vs = context.Vacancies.Where(x => x.Kind == "work" && !x.Viewed);
foreach (var v in vs) v.Viewed = true;
context.SaveChanges();
RenderWorkList();
}
public void answerWorkList_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
//button.IsEnabled = false;
var context = NewContext();
var v = context.Vacancies.FirstOrDefault(x => x.Id == (int)button.Tag);
v.Viewed = true;
var set = context.Settings.First();
set.LastVacancy = v.Id;
context.SaveChanges();
var p = prs.FirstOrDefault(x => x.Id == v.ProfileId);
Clipboard.SetText(config.letterWork.Replace("{n}", "\r\n"));
Task.Factory.StartNew(() =>
{
if (v.Site == "hh") AnswerHh(p, v);
});
RenderWorkList();
}
private void answerWorkList_Loaded(object sender, RoutedEventArgs e)
{
try
{
var button = sender as Button;
var v = workVacancies.FirstOrDefault(x => x.Id == (int)button.Tag);
if (v.Answered) button.Visibility = System.Windows.Visibility.Collapsed;
}
catch { }
}
private void workListGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
#endregion
#region Fl
private async void saveProfileFl_Click(object sender, RoutedEventArgs e)
{
saveProfileFl.Content = "Сохраняется...";
if (string.IsNullOrEmpty(profileFlCombo.Text)) { MessageBox.Show("Необходимо ввести название профиля", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; }
var context = NewContext();
var p = prs.FirstOrDefault(x => x.Name == profileFlCombo.Text && x.Kind == "fl");
if (p == null)
{
p = new Profile { Name = profileFlCombo.Text, Kind = "fl" };
prs.Add(p);
SaveConfig();
}
p.Search = searchFl.Text;
p.Answer = (bool)autoAnswerFl.IsChecked;
p.Remote = (bool)businessFl.IsChecked;
p.Proxy = proxyFl.Text;
p.Login = loginFreelance.Text;
p.Pass = passFreelance.Password;
p.LoginFlRu = loginFlRu.Text;
p.PassFlRu = passFlRu.Password;
p.freelanceru = (bool)freelanceru.IsChecked;
p.flru = (bool)flru.IsChecked;
SaveConfig();
RenderFlCombo();
saveProfileFl.Content = "Сохранено";
await Task.Delay(5000);
saveProfileFl.Content = "Сохранить профиль";
}
private void profileFlCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RenderFlText();
RenderFlList();
}
private void deleteProfileFl_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Удалить профиль?", "Вопрос", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
var context = NewContext();
var p = prs.FirstOrDefault(x => x.Name == profileFlCombo.Text && x.Kind == "fl");
if (p != null)
{
prs.Remove(p);
SaveConfig();
}
RenderFlCombo(true);
}
}
private void commaFl_Loaded(object sender, RoutedEventArgs e)
{
var text = sender as TextBlock;
var v = flVacancies.FirstOrDefault(x => x.Id == (int)text.Tag);
if (string.IsNullOrEmpty(v.Company)) text.Visibility = System.Windows.Visibility.Hidden;
}
private void flListGrid_MouseEnter(object sender, MouseEventArgs e)
{
var grid = sender as Grid;
grid.Style = (Style)FindResource("gridBackOver");
}
private void flListGrid_MouseLeave(object sender, MouseEventArgs e)
{
var grid = sender as Grid;
grid.Style = null;
}
public void detailFlList_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
int id = (int)button.Tag;
var context = NewContext();
var v = context.Vacancies.FirstOrDefault(x => x.Id == id);
v.Viewed = true;
var set = context.Settings.First();
set.LastVacancy = v.Id;
context.SaveChanges();
flVacancies.RemoveAll(x => x.Id == id);
RenderFlList();
}
private void allProfilesFl_Checked(object sender, RoutedEventArgs e)
{
//RenderFlList();
}
private void removeListFl_Click(object sender, RoutedEventArgs e)
{
var context = NewContext();
var vs = context.Vacancies.Where(x => x.Kind == "fl" && !x.Viewed);
foreach (var v in vs) { v.Viewed = true; flVacancies.RemoveAll(x => x.Id == v.Id); }
context.SaveChanges();
RenderFlList();
}
public void answerFlList_Click(object sender, RoutedEventArgs e)
{
try { Clipboard.SetText(config.letterFl.Replace("{n}", "\r\n")); } catch { }
var button = sender as Button;
int id = (int)button.Tag;
//button.IsEnabled = false;
var context = NewContext();
var v = context.Vacancies.FirstOrDefault(x => x.Id == id);
v.Viewed = true;
var set = context.Settings.First();
set.LastVacancy = v.Id;
context.SaveChanges();
flVacancies.RemoveAll(x => x.Id == id);
var p = prs.FirstOrDefault(x => x.Id == v.ProfileId);
Task.Factory.StartNew(() =>
{
if (v.Site == "freelance") AnswerFreelance(p, v);
if (v.Site == "flru") AnswerFlRu(p, v);
});
RenderFlList();
}
private void answerFlList_Loaded(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var v = flVacancies.FirstOrDefault(x => x.Id == (int)button.Tag);
if (v.Answered) button.Visibility = System.Windows.Visibility.Collapsed;
}
private void flListGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
private void dateFlList_Loaded(object sender, RoutedEventArgs e)
{
var t = sender as TextBlock;
var v = flVacancies.First(x => x.Id == (int)t.Tag);
t.Text = Helper.TimeAgo(v.Date, false);
}
private void DateOld_Checked(object sender, RoutedEventArgs e)
{
var el = sender as RadioButton;
config.dateSort = el.Name;
config.Save();
RenderFlList();
}
#endregion
#region Разное
void Log(string s, params object[] args)
{
if (args.Length > 0) s = string.Format(s, args);
s = DateTime.Now.ToString("G") + "=> " + s + "\r\n";
Dispatcher.BeginInvoke(new Action(() =>
{
log.AppendText(s);
log.ScrollToEnd();
}));
}
public void LoadConfig()
{
prs = Deserialize<List<Profile>>("prs");
if (prs == null) prs = new List<Profile>();
var dc = NewContext();
var d = DateTime.Now.AddDays(-7);
var recs = dc.Vacancies.Where(x => x.Date < d);
dc.Vacancies.RemoveRange(recs);
dc.SaveChanges();
flVacancies = dc.Vacancies.Where(x => x.Kind == "fl" && !x.Viewed).ToList();
flList.ItemsSource = flVacancies;
workList.ItemsSource = workVacancies;
popup.IsChecked = config.popup;
workEnabled.IsChecked = config.workEnabled;
flEnabled.IsChecked = config.flEnabled;
//RenderWorkCombo(true);
//RenderWorkList();
RenderFlCombo(true);
RenderFlList();
if (config.dateSort == "dateOld") dateOld.IsChecked = true; else dateNew.IsChecked = true;
var context = NewContext();
var set = context.Settings.FirstOrDefault();
if (set == null)
{
context.Settings.Add(new Setting());
context.SaveChanges();
}
}
public bool SaveConfig()
{
Serialize(prs, "prs");
config.Save();
return true;
}
ParserWc NewParser(Profile p)
{
var parser = new ParserWc(p.Proxy, 5000, p.Login + ".ck");
//parser.Fiddler = true;
return parser;
}
void HeadersMain(ParserWc parser)
{
parser.ClearHeaders();
parser.AddHeader("Sec-Fetch-Dest: document");
parser.AddHeader("Sec-Fetch-Mode: navigate");
parser.AddHeader("Sec-Fetch-Site: same-origin");
parser.AddHeader("Sec-Fetch-User: ?1");
parser.AddHeader("Upgrade-Insecure-Requests: 1");
}
void HeadersIndex(ParserWc parser)
{
parser.ClearHeaders();
parser.AddHeader("X-CSRF-Token", xcsrftoken);
parser.AddHeader("Sec-Fetch-Dest: empty");
parser.AddHeader("Sec-Fetch-Mode: cors");
parser.AddHeader("Sec-Fetch-Site: same-origin");
}
void HeadersPost(ParserWc parser)
{
parser.ClearHeaders();
parser.AddHeader("Origin", "https://id.freelance.ru");
parser.AddHeader("sec-ch-ua: \"Chromium\";v=\"146\", \"Not-A.Brand\";v=\"24\", \"YaBrowser\";v=\"26.4\", \"Yowser\";v=\"2.5\"");
parser.AddHeader("sec-ch-ua-mobile: ?0");
parser.AddHeader("sec-ch-ua-platform: \"Windows\"");
parser.AddHeader("Sec-Fetch-Dest: empty");
parser.AddHeader("Sec-Fetch-Mode: cors");
parser.AddHeader("Sec-Fetch-Site: same-origin");
}
public DataContext NewContext()
{
return new DataContext();
}
public async void Serialize(object o, string fileName)
{
while (true)
{
try
{
string s = JsonConvert.SerializeObject(o);
File.WriteAllText(string.Format("{0}{1}.json", Helper.PathCurrent, fileName), s, Encoding.UTF8);
break;
}
catch { await Task.Delay(100); }
}
}
T Deserialize<T>(string fileName)
{
T r = default(T);
string path = string.Format("{0}{1}.json", Helper.PathCurrent, fileName);
if (File.Exists(path))
{
string s = File.ReadAllText(path, Encoding.UTF8);
r = JsonConvert.DeserializeObject<T>(s);
}
return r;
}
#endregion
#region Render
void RenderWorkCombo(bool first = false)
{
Dispatcher.BeginInvoke(new Action(() =>
{
int index = profileWorkCombo.SelectedIndex;
profileWorkCombo.ItemsSource = null;
profileWorkCombo.ItemsSource = prs.Where(x => x.Kind == "work").ToList();
profileWorkCombo.DisplayMemberPath = "Name";
if (!first) profileWorkCombo.SelectedIndex = index;
if (first && profileWorkCombo.Items.Count > 0) profileWorkCombo.SelectedIndex = 0;
}));
}
void RenderWorkText()
{
Dispatcher.BeginInvoke(new Action(() =>
{
if (profileWorkCombo.SelectedIndex > -1)
{
var p = (Profile)profileWorkCombo.SelectedItem;
searchWork.Text = p.Search;
autoAnswerWork.IsChecked = p.Answer;
salaryWork.Text = p.Salary.ToString();
remote.IsChecked = p.Remote;
loginHh.Text = p.Login;
passHh.Password = p.Pass;
resumeLinkHh.Text = p.ResumeLinkHh;
proxyWork.Text = p.Proxy;
}
}));
}
void RenderWorkList()
{
Dispatcher.BeginInvoke(new Action(() =>
{
try
{
var context = NewContext();
if ((bool)allProfilesWork.IsChecked)
{
workVacancies = context.Vacancies.Where(x => x.Kind == "work" && !x.Viewed).ToList();
}
else if (profileWorkCombo.SelectedIndex > -1)
{
var p = (Profile)profileWorkCombo.SelectedItem;
workVacancies = context.Vacancies.Where(x => x.ProfileId == p.Id && !x.Viewed).ToList();
}
countWork.Text = workVacancies.Count.ToString();
workList.Items.Refresh();
}
catch { }
}));
}
void RenderFlCombo(bool first = false)
{
Dispatcher.BeginInvoke(new Action(() =>
{
int index = profileFlCombo.SelectedIndex;
profileFlCombo.ItemsSource = null;
profileFlCombo.ItemsSource = prs.Where(x => x.Kind == "fl").ToList();
profileFlCombo.DisplayMemberPath = "Name";
if (!first) profileFlCombo.SelectedIndex = index;
if (first && profileFlCombo.Items.Count > 0) profileFlCombo.SelectedIndex = 0;
}));
}
void RenderFlText()
{
Dispatcher.BeginInvoke(new Action(() =>
{
if (profileFlCombo.SelectedIndex > -1)
{
var p = (Profile)profileFlCombo.SelectedItem;
searchFl.Text = p.Search;
autoAnswerFl.IsChecked = p.Answer;
businessFl.IsChecked = p.Remote;
proxyFl.Text = p.Proxy;
loginFreelance.Text = p.Login;
passFreelance.Password = p.Pass;
loginFlRu.Text = p.LoginFlRu;
passFlRu.Password = p.PassFlRu;
freelanceru.IsChecked = p.freelanceru;
flru.IsChecked = p.flru;
}
}));
}
void RenderFlList()
{
/*var context = NewContext();
if ((bool)allProfilesFl.IsChecked)
{
flVacancies = context.Vacancies.Where(x => x.Kind == "fl" && !x.Viewed).OrderByDescending(x => x.Date).ToList();
}
else if (profileFlCombo.SelectedIndex > -1)
{
var p = (Profile)profileFlCombo.SelectedItem;
flVacancies = context.Vacancies.Where(x => x.ProfileId == p.Id && !x.Viewed).OrderByDescending(x => x.Date).ToList();
}*/
Dispatcher.BeginInvoke(new Action(() =>
{
if (config.dateSort == "dateOld") flVacancies.Sort((x, y) => x.Date.CompareTo(y.Date)); else flVacancies.Sort((x, y) => y.Date.CompareTo(x.Date));
countFl.Text = flVacancies.Count.ToString();
flList.Items.Refresh();
}));
}
#endregion
#region Парсинг
void StartWork()
{
if (config.workEnabled)
{
var context = NewContext();
var ps = prs.Where(x => x.Kind == "work");
foreach (var p in ps)
{
ParseHh(p);
}
Dispatcher.BeginInvoke(new Action(() => { updateWork.Text = "Последнее обновление: " + DateTime.Now.ToString("G"); }));
}
}
void StartFl()
{
if (config.flEnabled)
{
//Avito();
var context = NewContext();
var ps = prs.Where(x => x.Kind == "fl");
foreach (var p in ps)
{
if (p.freelanceru) ParseFreelance(p);
if (p.flru) ParseFlRu(p);
}
Dispatcher.BeginInvoke(new Action(() => { updateFl.Text = "Последнее обновление: " + DateTime.Now.ToString("G"); }));
}
}
void StartUpdateResume()
{
if (config.workEnabled)
{
var context = NewContext();
var ps = prs.Where(x => x.Kind == "work");
foreach (var p in ps)
{
List<Task> tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(() => UpdateResumeHh(p)));
Task.WaitAll(tasks.ToArray());
}
}
}
void Avito()
{
if (sw == null || sw.Elapsed.TotalHours > 1)
{
sw = Stopwatch.StartNew();
Task.Factory.StartNew(async () =>
{
try
{
await Dispatcher.BeginInvoke(new Action(() => { avito.Text = ""; }));
var p = new ParserWc();
p.Fiddler = true;
p.Go("https://www.avito.ru/krasnodarskiy_kray_yuzhnyy/kvartiry/sdam/na_dlitelnyy_srok-ASgBAgICAkSSA8gQ8AeQUg?s=104");
if (!string.IsNullOrEmpty(p.Error)) throw new Exception(p.Error);
var aa = p.SelectNodes("//div[@data-marker='catalog-serp']//a[@data-marker='item-title']");
if (aa != null)
{
var db = NewContext();
foreach (var a in aa)
{
string href = "https://www.avito.ru" + a.GetAttributeValue("href", "");
var rec = db.Vacancies.FirstOrDefault(x => x.Url == href);
if (rec == null)
{
string body = $"Новое объявление:<br><br>{href}";
await Mail("alexxxproof@gmail.com", "Avito", body);
db.Vacancies.Add(new Vacancy { Url = href, ProfileId = 1, Date = DateTime.Now });
db.SaveChanges();
}
}
}
await Dispatcher.BeginInvoke(new Action(() => { avito.Text = aa?.Count.ToString(); }));
}
catch (Exception ex) { await Dispatcher.BeginInvoke(new Action(() => { avito.Text = ex.Message; })); }
});
}
}
public static async Task Mail(string email, string subject, string message, List<string> attachments = null)
{
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(typeof(DataContext).Namespace, "alexxx6233@yandex.ru"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = message;
if (attachments != null) foreach (var a in attachments) builder.Attachments.Add(a);
emailMessage.Body = builder.ToMessageBody();
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.yandex.ru", 587, false);
await client.AuthenticateAsync("alexxx6233@yandex.ru", "Aqwsxz10");
await client.SendAsync(emailMessage);
await client.DisconnectAsync(true);
}
}
catch (Exception ex) { Helper.Log(ex); }
}
#endregion
#region hh
bool AuthHh(Profile p)
{
bool result = false;
try
{
var parser = NewParser(p);
parser.Go("http://" + RedirectHost(parser) + "/", false);
result = parser.Content.Contains("mainmenu_userName");
if (!result)
{
Log("{0} => Авторизация...", p.Login);
string _xsrf = parser.GetCookie("hh.ru", "_xsrf");
parser.Post("https://" + RedirectHost(parser) + "/account/login", string.Format("backUrl==%2F&failUrl=%2Faccount%2Flogin&username={0}&password={1}&remember=yes&_xsrf={2}", p.Login, p.Pass, _xsrf));