· 4 years ago · Mar 29, 2021, 08:04 AM
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Linq;
7using System.Text;
8using System.Threading;
9using System.IO;
10using System.Text.RegularExpressions;
11using ZennoLab.CommandCenter;
12using ZennoLab.InterfacesLibrary;
13using ZennoLab.InterfacesLibrary.ProjectModel;
14using ZennoLab.InterfacesLibrary.ProjectModel.Collections;
15using ZennoLab.InterfacesLibrary.ProjectModel.Enums;
16using ZennoLab.Macros;
17using Global.ZennoExtensions;
18using ZennoLab.Emulation;
19using System.IO;
20using System.Text.RegularExpressions;
21using System.Threading;
22using System.Globalization;
23using System.Net;
24using System.Linq;
25using System.Web;
26using System.Runtime.InteropServices;
27using Microsoft.Win32;
28using System.Drawing.Text;
29//using System.Collections.Immutable;
30
31using System.Xml.Serialization;
32
33using MouseEmulation.Native;
34using System.Drawing;
35using System.Runtime.InteropServices;
36
37using ZennoXml;
38
39using MouseEmulation;
40
41using OfficeOpenXml;
42using OfficeOpenXml.Style;
43
44namespace Emulate{
45
46 public static class CommonData{
47
48 public static bool Debug;
49
50 public static Random Random = new Random();
51
52 public static object Locker = new Object();
53
54 public static object ProfilesLocker = new Object();
55
56 public static bool IsDebug;
57
58 public static List<string> GetIpServices = new List<string>(){"http://checkip.amazonaws.com/", "http://ipinfo.io/ip", "http://bot.whatismyipaddress.com/", "http://icanhazip.com/", "http://api.ipify.org/"};
59
60 public static int CurrentHour;
61
62 public static int FirstMinute;
63
64 public static Dictionary<int, int> Schedule = new Dictionary<int, int>();
65
66 public static Mutex mutex = new Mutex(false, 'FarpostMutex');
67
68 public static void Cleanup(){
69 CurrentHour = 0;
70 FirstMinute = 0;
71 Schedule = new Dictionary<int, int>();
72 }
73
74 //void - ничего не возвращаем или string,int
75 //public - уровень доступности наших членов классов для других сборок или private
76 //static - необходимости или ее отсутствие экземпляра класса, динамический класс
77
78 public static List<string> YandexKeys = new List<string>();
79
80 public static int GetDifference(this DateTime Start_Date, DateTime End_Date){
81 System.TimeSpan Delta_Time = End_Date-Start_Date;
82 int Time_Difference = Delta_Time.Milliseconds;
83 Time_Difference = Time_Difference + Delta_Time.Seconds*1000;
84 Time_Difference = Time_Difference + Delta_Time.Minutes*60*1000;
85 Time_Difference = Time_Difference + Delta_Time.Hours*60*60*1000;
86 Time_Difference = Time_Difference + Delta_Time.Days*24*60*60*1000;
87 return Time_Difference;
88 }
89
90 public static bool CheckTimer_1(this int Timer) {
91 if (Timer > 40000) return true; else return false;
92 }
93
94 public static bool LoadWait(this Tab tab, int TimeOut){
95 DateTime now = DateTime.Now;
96 if(TimeOut >= 360000) return false; else return true;
97
98 }
99
100 public static Tab NavigateWithCheck(this Tab tab, string url, DateTime start, int NavigateTimeout = 16, string referer = ""){
101 //Фиксируем время начала работы
102 DateTime now = DateTime.Now;
103
104 //Время начало работы экшена
105 int Timer_Last = start.GetDifference(DateTime.Now);
106
107 //Проверяем на ошибку
108 if(Timer_Last.CheckTimer_1()) throw new Exception("Обнаружено замедление выполнения проекта = код 10_1, таймер = " + Timer_Last.ToString());
109 if(tab.IsVoid || tab.IsNull) throw new Exception("Обнаружена пустая вкладка - код 10_1");
110 //Таймаут загрузки страницы
111 tab.NavigateTimeout = NavigateTimeout;
112 tab.Navigate(url, referer);
113
114 //Проверка на ошибки
115 Timer_Last = now.GetDifference(DateTime.Now);
116 now = DateTime.Now;
117 if(Timer_Last.CheckTimer_1()) throw new Exception("Обнаружено замедление выполнения проекта = код 10_2, таймер = " + Timer_Last.ToString());
118 if(tab.IsVoid || tab.IsNull) throw new Exception("Обнаружена пустая вкладка - код 10_2");
119
120 LoadWait(tab, 8);
121
122 return tab;
123 }
124
125 // Stop загрузки
126 public static Tab StopWithCheck(this Tab tab, DateTime start) {
127
128 // запоминаем время начала работы экшена
129 DateTime now = DateTime.Now; int Timer_Last=start.GetDifference(DateTime.Now);
130 //Проверка на ошибки
131 if ( Timer_Last.CheckTimer_1() ) throw new Exception("Обнаружено замедление выполнения проекта - код 4_1, таймер = " + Timer_Last.ToString() );
132 if ( tab.IsVoid || tab.IsNull ) throw new Exception("Обнаружена пустая вкладка - код 4_1");
133 //
134 tab.Stop();
135 //Проверка на ошибки
136 Timer_Last= now.GetDifference(DateTime.Now);
137 if ( Timer_Last.CheckTimer_1() ) throw new Exception("Обнаружено замедление выполнения проекта - код 4_2, таймер = " + Timer_Last.ToString() );
138 if ( tab.IsVoid || tab.IsNull ) throw new Exception("Обнаружена пустая вкладка - код 4_2, таймер = " + Timer_Last.ToString() );
139 return tab;
140 }
141 }
142
143 public class Thread{
144
145 public Thread(IZennoPosterProjectModel newProject, Instance newInstance){
146 project = newProject;
147 instance = newInstance;
148 }
149
150 public IZennoPosterProjectModel project;
151
152 public Instance instance;
153
154 }
155
156 public class Worker{
157
158 public Worker(Emulate.Thread thread){
159 Thread = thread;
160 project = Thread.project;
161 instance = Thread.instance;
162
163 webH = new WebHelper(instance, project, false);
164
165 }
166
167 public WebHelper webH;
168
169 private IZennoPosterProjectModel project;
170 private Instance instance;
171 public Emulate.Thread Thread;
172
173 public void ScrollToElement(Tab tab, string targetXpath, int index=0, int minTopSpace=200) {
174
175 HtmlElement element = tab.FindElementByXPath(targetXpath, index);
176 if (element.IsVoid) return;
177
178 if(Mobile) {
179 tab.FullEmulationMouseWheel(element); //tab.Touch.SwipeIntoView(element);
180 }else{
181 tab.FullEmulationMouseWheel(element);
182 }
183
184// minTopSpace += CommonData.Random.Next(0, 150);
185//
186// HtmlElement target = tab.FindElementByXPath(targetXpath, index);
187// if (target.DisplacementInTabWindow.Y>100 && target.DisplacementInTabWindow.Y < 300) return;
188//
189// int maxSteps = 100;
190// while(true){
191// if (--maxSteps<1) break;
192//
193// target = tab.FindElementByXPath(targetXpath, index);
194//
195// if (target.IsVoid){
196// tab.MouseWheel(tab.FullEmulationMouseCurrentPosition.X, tab.FullEmulationMouseCurrentPosition.Y, 0, 50);
197// System.Threading.Thread.Sleep(CommonData.Random.Next(15, 25));
198// }else{
199// if (target.DisplacementInTabWindow.Y>minTopSpace && target.DisplacementInTabWindow.Y<minTopSpace+150) break;
200//
201// bool directionDown = target.DisplacementInTabWindow.Y+minTopSpace>tab.FullEmulationMouseCurrentPosition.Y;
202//
203// int before = target.DisplacementInTabWindow.Y;
204//
205// tab.MouseWheel(tab.FullEmulationMouseCurrentPosition.X, tab.FullEmulationMouseCurrentPosition.Y, 0, directionDown?50:-50);
206// System.Threading.Thread.Sleep(CommonData.Random.Next(15, 25));
207//
208// target = tab.FindElementByXPath(targetXpath, index);
209// if (target.DisplacementInTabWindow.Y==before) break;
210// }
211// }
212//
213// System.Threading.Thread.Sleep(2000);
214
215 }
216
217 private string GenerateRandomString(int LenghthFrom = 8, int LenghtTo = 12, bool UseAllAllowedSymbols = true,
218 bool BigLat = true, bool SmallLat = true, bool Numbers = true, bool BigRus = false, bool SmallRus = false, string Specsymbols = "")
219 {
220
221 Random rndTextGenerator = CommonData.Random;
222 string strRandom = String.Empty;
223 int intStringLength = 22;
224
225 intStringLength = rndTextGenerator.Next(LenghthFrom, LenghtTo + 1);
226
227 string[] arrDictionary = new String[6];
228 arrDictionary[0] = BigLat ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ" : "";
229 arrDictionary[1] = SmallLat ? "abcdefghijklmnopqrstuvwxyz" : "";
230 arrDictionary[2] = Numbers ? "0123456789" : "";
231 arrDictionary[3] = BigRus ? "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ" : "";
232 arrDictionary[4] = SmallRus ? "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" : "";
233 arrDictionary[5] = Specsymbols;
234
235 string strSymbols = String.Join(String.Empty, arrDictionary);
236 char[] arrChars = new char[intStringLength];
237 for (int i = 0; i < arrChars.Length; i++)
238 {
239 arrChars[i] = strSymbols[rndTextGenerator.Next(strSymbols.Length)];
240 }
241 strRandom = String.Join(String.Empty, arrChars);
242 if (!UseAllAllowedSymbols) return strRandom;
243
244 if (arrChars.Length >= arrDictionary.Length)
245 {
246 for (int i = 0; i < arrDictionary.Length; i++)
247 {
248 if (arrDictionary[i] != String.Empty)
249 {
250 arrChars[i] = Convert.ToChar(arrDictionary[i].Substring(rndTextGenerator.Next(0, arrDictionary[i].Length), 1));
251 }
252 }
253 }
254 strRandom = String.Join(String.Empty, arrChars);
255
256 return strRandom;
257 }
258
259 public void Initialize(){
260
261 if (CommonData.Debug) project.SendWarningToLog("Initialize: запуск метода (debug)", true);
262
263 Tab tab = instance.ActiveTab;
264 Random rnd = new Random();
265 if (CommonData.Debug) project.SendWarningToLog("Initialize: 1 (debug)", true);
266
267 CheckBindFiles();
268
269 instance.ClearCache();
270 instance.ClearCookie();
271 if (CommonData.Debug) project.SendWarningToLog("Initialize: 2 (debug)", true);
272 //GetKey();
273
274 //GetProfile();
275
276 try{
277 if (CommonData.Debug) project.SendWarningToLog("Initialize: 3 (debug)", true);
278 //SetProxy();
279 instance.SetProxy(""); //Только для отладки
280 }catch(Exception e){
281 if (CommonData.Debug) project.SendWarningToLog("Initialize: 4 (debug)", true);
282 string profile = project.Variables["Login"].Value;
283 if (!String.IsNullOrWhiteSpace(profile) && File.Exists(profile)) {
284 FileInfo file = new FileInfo(profile);
285 file.CopyTo(project.Directory + @"\profiles\" + file.Name, true);
286 file.Delete();
287 }
288 if (CommonData.Debug) project.SendWarningToLog("Initialize: 5 (debug)", true);
289 throw e;
290 }
291 //CheckMobile();
292
293 TuneBrowser();
294
295 //project.SendInfoToLog("Используем профиль " + project.Profile.Login, true);
296
297 //Задаем кривую для тача
298 //float curve = rnd.Next(0.10, 0.92);
299
300// if (CommonData.Debug) project.SendWarningToLog("Touch Parameters: определяем значение кривой (debug)", true);
301// ZennoLab.CommandCenter.TouchEvents.TouchEmulationParameters parameters = new ZennoLab.CommandCenter.TouchEvents.TouchEmulationParameters();
302// //var parameters = tab.Touch.GetCopyOfTouchEmulationParameters();
303//
304// Single curve = (float)rnd.Next(5, 10)/10;
305// parameters.RightThumbProbability = curve; //% движения пальцами (большой и указательный)
306// tab.Touch.SetTouchEmulationParameters(parameters);
307
308// if (CommonData.Debug) project.SendWarningToLog("Touch Parameters: значение кривой определено (debug)", true);
309
310 if (CommonData.Debug) project.SendWarningToLog("Initialize: завершение метода (debug)", true);
311
312 }
313
314 public void CheckBindFiles(){
315
316 if(CommonData.Debug) project.SendWarningToLog("Запуск метода: CheckBindFiles",true);
317
318 Random rnd = new Random();
319
320 List<string> voidFiles = new List<string>();
321
322 if(CommonData.Debug) project.SendWarningToLog("CheckBindFiles: 1",true);
323
324// string proxy_file = project.ExecuteMacro(project.Variables["proxy_file"].Value);
325
326// if(CommonData.Debug) project.SendWarningToLog("CheckBindFiles: 2",true);
327// if (voidFiles.Count>0){
328// project.SendErrorToLog("Отсутсвует 1 или более файлов настройки: \r\n" + String.Join(Environment.NewLine, voidFiles), true);
329// throw new Exception();
330// }
331
332 if(CommonData.Debug) project.SendWarningToLog("CheckBindFiles: 3",true);
333
334 int rnd_pause1 = Convert.ToInt32(project.Variables["rnd_pause1"].Value);
335 int rnd_pause2 = Convert.ToInt32(project.Variables["rnd_pause2"].Value);
336
337 int rnd_pause_fin = rnd.Next(rnd_pause1, rnd_pause2)*1000;
338
339 if(CommonData.Debug) project.SendWarningToLog("CheckBindFiles: 4",true);
340
341 project.SendInfoToLog("Пауза перед запуском следующего потока - " + Convert.ToInt32(rnd_pause_fin/1000) + " сек.", true);
342 System.Threading.Thread.Sleep(rnd_pause_fin);
343
344 if(CommonData.Debug) project.SendWarningToLog("Завершение метода: CheckBindFiles",true);
345
346 }
347
348 public bool Mobile;
349
350 public void TuneBrowser(){
351
352 if (CommonData.Debug) project.SendWarningToLog("TuneBrowser: запуск метода (debug)", true);
353
354 instance.SetWindowSize(project.Profile.AvailScreenWidth, project.Profile.AvailScreenHeight);
355
356 //instance.ShowNavigatorField(ZennoLab.InterfacesLibrary.Enums.Browser.NavigatorField.DoNotTrack);
357// if (new Random().Next(0, 100)>70) {
358// project.SendInfoToLog("Включили DoNotTrack (выполняется в 30% случаев)", true);
359// instance.SetHeader(ZennoLab.InterfacesLibrary.Enums.Browser.NavigatorField.DoNotTrack, "null"); // Включает Do Not Track
360// }
361
362// instance.LoadPictures = true;
363// instance.UsePlugins = true;
364// instance.UsePluginsForceWmode = true;
365
366// instance.IgnoreAjaxRequests = true;
367// instance.IgnoreAdditionalRequests = true;
368// instance.IgnoreFrameRequests = true;
369// instance.IgnoreFlashRequests = true;
370
371// instance.UseMedia = true;
372// instance.UseMedia = true;
373// instance.UseMedia = true;
374// instance.UseMedia = true;
375// instance.SetContentPolicy("DirectLoad", null, null);
376
377// instance.WebRTCWorkMode = ZennoLab.InterfacesLibrary.Enums.Browser.WebRTCMode.Disable;
378// instance.UseGeoposition = false;
379
380 if (CommonData.Debug) project.SendWarningToLog("TuneBrowser: завершение метода (debug)", true);
381
382 }
383
384 public void CheckMobile(){
385
386 if (CommonData.Debug) project.SendWarningToLog("CheckMobile: запуск метода (debug)", true);
387
388 bool isMobile = false;
389
390 try{
391
392 string UA = new Regex(@"(?<=\ \().*?(?=\)\ )").Match(project.Profile.UserAgent).Value;
393
394 if (CommonData.Debug) project.SendWarningToLog("UA: + " + UA + " + (debug)", true);
395
396 if(UA.Contains("Apple")) isMobile=true;
397 if(UA.Contains("Android")) isMobile=true;
398 if(UA.Contains("iPad")) isMobile=true;
399
400 if (isMobile) {
401 project.SendInfoToLog("Работаем с mobile выдачей", true);
402
403 int xSize1 = project.Profile.AvailScreenWidth;
404 int ySize1 = project.Profile.AvailScreenHeight;
405
406// if(xSize>=ySize){
407// project.SendWarningToLog("Ширина устанавливаемого мобильного устройства больше высоты, прерываем установку размера инстанса, перезапускаем шаблон", true);
408// return;
409// }
410
411 instance.SetWindowSize(xSize1, ySize1);
412 project.SendInfoToLog("Установлен размер инстанса: " + Convert.ToString(xSize1) + ", " + Convert.ToString(ySize1), true);
413
414 }else{
415 project.SendInfoToLog("Работаем с декстоп выдачей", true);
416 int xSize = project.Profile.ScreenSizeWidth-50;
417 if (xSize>1920) xSize = 1850;
418
419 int ySize = project.Profile.ScreenSizeHeight-50;
420 if (ySize>1080) ySize = 1030;
421
422 instance.SetWindowSize(CommonData.Random.Next(1100, xSize), CommonData.Random.Next(750, ySize));
423
424 int xSize2 = project.Profile.AvailScreenWidth;
425 int ySize2 = project.Profile.AvailScreenHeight;
426
427 instance.SetWindowSize(xSize2, ySize2);
428 project.SendInfoToLog("Установлен размер инстанса: " + Convert.ToString(xSize2) + ", " + Convert.ToString(ySize2), true);
429 }
430 }catch{}
431
432 Mobile = isMobile;
433
434 webH.Mobile = isMobile;
435
436 if (CommonData.Debug) project.SendWarningToLog("CheckMobile: завершение метода (debug)", true);
437 }
438
439 public void SiteView(){
440
441 if (CommonData.Debug) project.SendWarningToLog("SiteView: запуск метода (debug)", true);
442
443 Random rnd = new Random();
444
445 MouseEmulator.instance = instance;
446 MouseEmulator.project = project;
447
448 string competitor = project.Variables["competitor"].Value;
449
450 WebHelper webH = new WebHelper(instance, project, Mobile);
451
452 List<string> hrefBL = project.Lists["hrefBL"].ToList();
453
454 int time_adv_from = Convert.ToInt32(project.Variables["time_adv_from"].Value);
455 int time_adv_to = Convert.ToInt32(project.Variables["time_adv_to"].Value);
456
457 int TimeOnSite = rnd.Next(time_adv_from, time_adv_to);
458 DateTime TotalSiteTime = DateTime.Now.AddSeconds(TimeOnSite);
459
460 if (CommonData.Debug) project.SendWarningToLog("SiteView: 1 (debug)", true);
461
462 try{MouseWheel2();}catch{}
463
464 while(DateTime.Now<TotalSiteTime) {
465
466 Tab tab = instance.ActiveTab;
467
468 List<HtmlElement> paragraphs = new List<HtmlElement>();
469 DateTime timeout = DateTime.Now.AddSeconds(5);
470 while(DateTime.Now<timeout) {
471
472 paragraphs = tab.FindElementsByXPath("//p[string-length(text())>25]").ToList();
473
474 if (paragraphs.Count>0) break;
475 System.Threading.Thread.Sleep(125);
476 }
477
478 List<HtmlElement> links = new List<HtmlElement>();
479 timeout = DateTime.Now.AddSeconds(5);
480 while(DateTime.Now<timeout) {
481
482 links = tab.FindElementsByXPath("//a[@href]|//button").ToList();
483
484 if (links.Count>0) break;
485 System.Threading.Thread.Sleep(125);
486 }
487
488 if (CommonData.Debug) project.SendWarningToLog("SiteView: 1_2 (debug)", true);
489
490 paragraphs.Shuffle();
491 paragraphs = paragraphs.Take(15).ToList();
492
493 paragraphs.RemoveAll(x=>
494 {
495 foreach(string bl in hrefBL) {
496 if (x.InnerText.Contains(bl)) return true;
497 }
498 return false;
499 });
500
501 if (CommonData.Debug) project.SendWarningToLog("SiteView: 1_3 (debug)", true);
502
503 links = links.Skip(10).Take(15).ToList();
504 links.Shuffle();
505
506 links.RemoveAll(x=>
507 {
508 foreach(string bl in hrefBL) {
509 if (x.GetAttribute("class").Contains(bl)) return true;
510
511 string link = x.GetAttribute("href");
512 if (!String.IsNullOrWhiteSpace(link) && link.Contains(bl)) return true;
513
514 }
515 return false;
516 });
517
518 if (CommonData.Debug) project.SendWarningToLog("SiteView: 1_4 (debug)", true);
519
520 List<HtmlElement> CardsView = new List<HtmlElement>();
521 CardsView.AddRange(paragraphs);
522 CardsView.AddRange(links);
523 CardsView.Shuffle();
524
525 var Count = CardsView.Count();
526 if (CommonData.Debug) project.SendWarningToLog("Тегов для чтения на странице сайта - " + Convert.ToString(Count), true);
527
528 if (CommonData.Debug) project.SendWarningToLog("SiteView: 2 (debug)", true);
529
530 if(Count>0){
531
532 int cards_to_view = rnd.Next(1, rnd.Next(5,10));
533 if (CommonData.Debug) project.SendWarningToLog("SiteView: Тегов для просмотра - " + cards_to_view + " (debug)", true);
534
535 if(cards_to_view>=Count){
536 cards_to_view=Count;
537 }else{
538 project.SendInfoToLog("Продолжаем работу..", true);
539 }
540 if (CommonData.Debug) project.SendWarningToLog("SiteView: 3 (debug)", true);
541
542 for(int k=1;k<=cards_to_view;k++){
543
544 if (CardsView.Count==0) break;
545 HtmlElement LoneElm = CardsView[0];
546 CardsView.RemoveAt(0);
547
548 if(Mobile){
549 if (CommonData.Debug) project.SendWarningToLog("SiteView: Mobile (debug)", true);
550
551 tab.Touch.SwipeIntoView(LoneElm);
552
553 if(LoneElm.TagName=="a"){
554 project.SendInfoToLog(LoneElm.TagName);
555 tab.Touch.Touch(LoneElm);
556
557 System.Threading.Thread.Sleep(500);
558 if (instance.ActiveTab.Handle!=tab.Handle) instance.ActiveTab.Close();
559 }
560
561 if (CommonData.Debug) project.SendWarningToLog("SiteView: 5 (debug)", true);
562 }else{
563 if (CommonData.Debug) project.SendWarningToLog("SiteView: Desktop (debug)", true);
564
565 tab.FullEmulationMouseWheel(LoneElm, rnd.Next(10,15), rnd.Next(10,15));
566
567 if(LoneElm.TagName=="a"){
568 tab.FullEmulationMouseClick("left","click");
569
570 System.Threading.Thread.Sleep(500);
571 if (instance.ActiveTab.Handle!=tab.Handle) instance.ActiveTab.Close();
572 }
573
574 if (CommonData.Debug) project.SendWarningToLog("SiteView: 6 (debug)", true);
575 }
576
577 try{ClosePopup();}catch{}
578
579 string NowPage = instance.ActiveTab.DomText;
580 string YaErrPage = Regex.Match(NowPage, @"(?<=jstcache='10'>).*(?=</span>)").ToString();
581
582 if(YaErrPage=="This site can't be reached"){
583 project.SendWarningToLog("Яндекс выдал ошибку - This site can’t be reached, закрываем сайт, продолжаем работу с ПС",true);
584 System.Threading.Thread.Sleep(rnd.Next(500,900));
585 CloseAllTabs();
586 return;
587 }
588 }
589
590 }else{
591 try{MouseWheel2();}catch{}
592 }
593 }
594
595 CloseAllTabs();
596
597 if (CommonData.Debug) project.SendWarningToLog("SiteView: завершение метода (debug)", true);
598 }
599
600 public void Cleanup(){
601
602 if (CommonData.Debug) project.SendWarningToLog("Cleanup: запуск метода (debug)", true);
603
604 if (project.Variables["proxy_select"].Value=="Unicorn" && !String.IsNullOrWhiteSpace(project.Variables["proxy_session_id"].Value)){
605
606 try{
607 Unicorn.AirProxyClient ProxyClient = new Unicorn.AirProxyClient("artseoemulator", 1, 180, 1200, project.Variables["airpoxy_project_path"].Value);
608 ProxyClient.SearchValue = project.Variables["proxy_session_id"].Value;
609 ProxyClient.RunCommand("release_proxy", 60);
610 project.SendInfoToLog(ProxyClient.ResultMessage, true);
611 }catch(Exception e){
612 throw new Exception("Ошибка при освобождении прокси от Unicorn AirProxy: " + e.Message);
613 }
614
615 }
616
617 if (CommonData.Debug) project.SendWarningToLog("Cleanup: завершение метода (debug)", true);
618
619 }
620
621 public void SetProxy(){
622
623 Random rnd = new Random();
624
625 if (CommonData.Debug) project.SendWarningToLog("SetProxy: запуск метода (debug)", true);
626
627 if (project.Variables["proxy_yes"].Value!="Да") return;
628
629 string proxy = String.Empty;
630 if (project.Variables["proxy_select"].Value=="Unicorn"){
631 string path = project.Variables["airpoxy_project_path"].Value;
632 project.SendWarningToLog("Путь к airproxy - " + path, true);
633 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 1 (debug)", true);
634 if (String.IsNullOrWhiteSpace(path)) throw new Exception("не указан путь к шаблону Unicorn или ссылка на API");
635
636 //получаем Unicorn proxy
637 try{
638 DateTime proxyStart = DateTime.Now;
639 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 2 (debug)", true);
640 Unicorn.AirProxyClient ProxyClient = new Unicorn.AirProxyClient("artseokirill", 1, 0, 1200, path);
641 ProxyClient.RunCommand("take_http_proxy", 180);
642 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 3 (debug)", true);
643 project.Variables["proxy_session_id"].Value = ProxyClient.SearchValue;
644 project.SendInfoToLog(ProxyClient.ResultMessage, true);
645 proxy = ProxyClient.Result;
646 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 4 (debug)", true);
647 if (CommonData.Debug) project.SendInfoToLog(String.Format("Прокси от Unicorn получен за {0} секунд. Id прокси-сессии: {1}", DateTime.Now.Subtract(proxyStart).TotalSeconds, ProxyClient.SearchValue), true);
648 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 5 (debug)", true);
649 if (path.Contains("http")){
650 string extIp = new Regex(@"(?<=http://).*?(?=:)").Match(path).Value;
651 string proxyIp = new Regex(@"(?<=(//|@))\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?=:)").Match(proxy).Value;
652 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 6 (debug)", true);
653 proxy = proxy.Replace(proxyIp, extIp);
654 project.SendWarningToLog("Значение Proxy - " + proxy, true);
655 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 7 (debug)", true);
656 }
657 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 8 (debug)", true);
658 }catch(Exception e){
659 string errorDescription = "Ошибка при получении прокси от Unicorn AirProxy: " + e.Message;
660 project.SendErrorToLog(errorDescription, true);
661 throw new Exception(errorDescription);
662 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 9 (debug)", true);
663 }
664
665 }else{
666 //Получаем прокси из списка
667 IZennoList proxies = project.Lists["lst_proxies"];
668 if (proxies.Count==0) throw new Exception("список прокси пуст");
669 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 10 (debug)", true);
670 lock(SyncObjects.ListSyncer){
671 for(int i=0; i<100; i++){
672 proxy = proxies[0];
673 proxies.RemoveAt(0);
674 if (String.IsNullOrWhiteSpace(proxy)) continue;
675 proxies.Add(proxy);
676 break;
677 }
678 if(String.IsNullOrWhiteSpace(proxy)) throw new Exception("В файле прокси содержатся только пустые строки");
679 }
680 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 11 (debug)", true);
681 string[] proxyData = proxy.Split(';');
682 if (proxyData.Length>1){
683 proxy = proxyData[0];
684 project.SendInfoToLog("Меняем адрес прокси.", true);
685
686 project.SendInfoToLog("Пауза 60 сек. перед сменой IP прокси...", true);
687
688 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 11_1 (debug)", true);
689 string changeIpResult = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.GET, proxyData[1],
690 respType: ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly, throwExceptionOnError: true);
691
692 System.Threading.Thread.Sleep(40000);
693 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 12 (debug)", true);
694 project.SendInfoToLog("Закончили смену адреса прокси.", true);
695 }
696 }
697
698 project.Variables["proxy"].Value = proxy;
699 project.SendInfoToLog("Ставим прокси " + proxy, true);
700 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 13 (debug)", true);
701 if (project.Variables["advanced_chek_proxy"].Value=="False") {
702 project.SendInfoToLog("Установка прокси с дополнительной проверкой", true);
703
704 Regex rxIp = new Regex(@"(?<=ip"":\ "").*?(?="")"); //https://airvpn.org/forums/topic/14737-api/
705
706 int proxiesTriesLeft = 5;
707
708 if (String.IsNullOrWhiteSpace(proxy)){
709 throw new Exception("Строка прокси пуста!");
710 }
711 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 14 (debug)", true);
712 //устанавливаем таймзону
713 string timeZone = String.Empty;
714 Regex rxTZ = new Regex(@"(?<=time_zone"":\ "").*?(?="")");
715
716 while (true){
717 try{
718 instance.SetProxy("");
719 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 15 (debug)", true);
720 Tab Tab1 = instance.ActiveTab;
721 Tab1.NavigateWithCheck("https://ipleak.net/json/", DateTime.Now, 60);
722 Tab1.WaitDownloading();
723 string prevIp = rxIp.Match(Tab1.MainBody.InnerText).Value;
724
725 if (String.IsNullOrWhiteSpace(proxy)) throw new Exception("Получена пустая строка прокси");
726 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 16 (debug)", true);
727 instance.SetProxy(proxy, false, false, false, false);
728 System.Threading.Thread.Sleep(rnd.Next(500, 1200));
729
730 project.SendInfoToLog("Установлен прокси - " + project.GetProxy(), true);
731 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 17 (debug)", true);
732 if(String.IsNullOrWhiteSpace(project.GetProxy())){
733 if (CommonData.Debug) project.SendWarningToLog("SetProxy: Try - обнаружена пустая строка прокси, ставим еще раз.. (debug)", true);
734 System.Threading.Thread.Sleep(rnd.Next(500, 1200));
735 instance.SetProxy(proxy, false, false, false, false);
736 System.Threading.Thread.Sleep(rnd.Next(500, 1200));
737 if(!String.IsNullOrWhiteSpace(project.GetProxy())){
738 project.SendInfoToLog("Установлен прокси - " + proxy, true);
739 }else{
740 project.SendWarningToLog("Не удалось установить прокси..", true);
741 }
742 }
743 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 18 (debug)", true);
744 Tab1.NavigateWithCheck("https://ipleak.net/json/", DateTime.Now, 60);
745 Tab1.WaitDownloading();
746
747 string newIp = rxIp.Match(Tab1.MainBody.InnerText).Value;
748 timeZone = rxTZ.Match(Tab1.MainBody.InnerText).Value.Replace(@"\", String.Empty);
749 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 19 (debug)", true);
750 if (CommonData.Debug) project.SendWarningToLog(String.Format("SetProxy: {0} -> {1}", prevIp, newIp), true);
751
752 if (String.IsNullOrWhiteSpace(newIp) || String.IsNullOrWhiteSpace(timeZone)) {
753 throw new Exception("Не удалось получить IP-адрес или таймзону после установки прокси (нерабочий прокси-сервер, либо ошибка на стороне сервиса получения гео?))");
754 }
755 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 20 (debug)", true);
756 if (newIp==prevIp) throw new Exception("После смены прокси IP-адрес не изменился!");
757 break;
758 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 21 (debug)", true);
759 }catch (Exception e){
760 string errDesc = "Ошибка при установке прокси: " + e.Message;
761 if (--proxiesTriesLeft>0){
762 project.SendWarningToLog(errDesc, true);
763 }else{
764 throw new Exception(errDesc);
765 }
766 }
767
768 System.Threading.Thread.Sleep(20000);
769 }
770
771 instance.SetIanaTimezone(timeZone, ZennoLab.InterfacesLibrary.Enums.Browser.TimezoneMode.Emulate);
772 project.SendInfoToLog("Установили таймзону " + timeZone, true);
773 }else{
774 instance.SetProxy(proxy, false, false, false, false);
775 System.Threading.Thread.Sleep(rnd.Next(500, 1200));
776 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 22 (debug)", true);
777 project.SendInfoToLog("Установлен прокси - " + project.GetProxy(), true);
778
779 if(String.IsNullOrWhiteSpace(project.GetProxy())){
780 if (CommonData.Debug) project.SendWarningToLog("SetProxy: Try - обнаружена пустая строка прокси, ставим еще раз.. (debug)", true);
781 System.Threading.Thread.Sleep(rnd.Next(500, 1200));
782 instance.SetProxy(proxy, false, false, false, false);
783 System.Threading.Thread.Sleep(rnd.Next(500, 1200));
784 if(!String.IsNullOrWhiteSpace(project.GetProxy())){
785 project.SendInfoToLog("Установлен прокси - " + proxy, true);
786 }else{
787 project.SendWarningToLog("Не удалось установить прокси..", true);
788 }
789 if (CommonData.Debug) project.SendWarningToLog("SetProxy: 23 (debug)", true);
790 }
791 }
792
793 if (CommonData.Debug) project.SendWarningToLog("SetProxy: завершение метода (debug)", true);
794 }
795
796 public void GetProfile(){
797
798 if (CommonData.Debug) project.SendWarningToLog("GetProfile: запуск метода (debug)", true);
799
800 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 1 (debug)", true);
801
802 int days_gone = Convert.ToInt32(project.Variables["days_gone"].Value);
803 int hour_gone = Convert.ToInt32(project.Variables["hour_gone"].Value);
804 int min_prof_size = Convert.ToInt32(project.Variables["min_prof_size"].Value);
805
806 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 2 (debug)", true);
807
808 try{
809 FileInfo goodProfile = null;
810
811 lock(SyncObjects.ListSyncer){
812
813 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 3 (debug)", true);
814
815 int minProfileSize = 1024 * min_prof_size; //Размер в килобайтах
816 DateTime walkIntervalPeriod = DateTime.Now.AddDays(-days_gone); //дни (интервал до истечения которого профиль берётся в работу, после истечения перемещается для разового нагула).
817
818 DateTime useIntervalPeriod = DateTime.Now.AddHours(-hour_gone); //часы (интервал в котором профиль не будет браться после последнего использования)
819 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 4 (debug)", true);
820
821 DirectoryInfo profilesDir = new DirectoryInfo(project.Directory + @"\profiles\");
822 List<FileInfo> profiles = profilesDir.GetFiles("*.zpprofile", SearchOption.TopDirectoryOnly).ToList();
823 if (profiles.Count==0) {
824 //если профилей нет - пробуем забрать отработанные из папки done (те которые были использованы более 12 часов назад)
825 DirectoryInfo doneDir = new DirectoryInfo(project.Directory + @"\profiles\done\");
826 foreach (FileInfo done in doneDir.GetFiles("*.zpprofile", SearchOption.TopDirectoryOnly).Where(x=>x.LastWriteTime>useIntervalPeriod)) {
827 done.CopyTo(project.Directory + @"\profiles\" + done.Name, true);
828 done.Delete();
829 }
830 profiles = profilesDir.GetFiles("*.zpprofile", SearchOption.TopDirectoryOnly).ToList();
831 }
832
833 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 5 (debug)", true);
834
835 DirectoryInfo forWalk = new DirectoryInfo(project.Directory + @"\profiles\for_walk\");
836 if (!forWalk.Exists) forWalk.Create();
837
838 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 6 (debug)", true);
839
840 //перемещаем все "мелкие" профили в папку для нагуливания
841 foreach (FileInfo mini in profiles.Where(x=>x.Exists && x.Length<minProfileSize)) {
842 project.SendInfoToLog(forWalk.FullName + @"\" + mini.Name);
843 mini.CopyTo(forWalk.Name + mini.Name, true);
844 mini.Delete();
845 }
846
847 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 7 (debug)", true);
848
849 //перемещаем все профили которые гуляли более n дней назад в папку для нагуливания
850 foreach (FileInfo mini in profiles.Where(x=>x.Exists && x.LastWriteTime<walkIntervalPeriod)) {
851 mini.CopyTo(forWalk.FullName + mini.Name, true);
852 mini.Delete();
853 }
854
855 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 8 (debug)", true);
856
857 //Пробуем получить профиль для текущей работы
858 List<FileInfo> walked = profiles.Where(x=>x.Exists && x.Length>=minProfileSize && x.LastWriteTime>walkIntervalPeriod).Shuffle().ToList();
859 if (walked.Count==0) {
860 throw new Exception("Нет профилей пригодных для работы");
861 }else{
862 project.SendInfoToLog("Профилей пригодных для работы: " + walked.Count, true);
863 }
864
865 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 9 (debug)", true);
866
867 FileInfo profile = walked[0];
868
869 DirectoryInfo forWork = new DirectoryInfo(project.Directory + @"\profiles\work\");
870 if (!forWork.Exists) forWork.Create();
871
872 goodProfile = profile.CopyTo(forWork.FullName + profile.Name, true);
873 profile.Delete();
874
875 }
876
877 if (CommonData.Debug) project.SendWarningToLog("GetProfile: 10 (debug)", true);
878 project.Variables["Login"].Value = goodProfile.FullName;
879 project.SendInfoToLog("Работаем с профилем " + goodProfile.Name, true);
880 DateTime loadStart = DateTime.Now;
881 project.Profile.Load(goodProfile.FullName);
882
883 if(instance.ScreenResolution.Width==50505){
884 string PathToProfile = project.Variables["Login"].Value;
885 project.SendWarningToLog("Обнаружена ошибка 50505 в профиле - " + PathToProfile + " профиль удален.", true);
886 System.IO.File.Delete(PathToProfile);
887 throw new Exception();
888 }
889
890 int loadSeconds = Convert.ToInt32(DateTime.Now.Subtract(loadStart).TotalSeconds);
891
892 if (CommonData.Debug) project.SendInfoToLog(String.Format("Профиль загружен за {0} секунд", loadSeconds), true);
893 if (loadSeconds>120) {
894 project.SendWarningToLog("Время загрузки профиля " + project.Variables["Login"].Value + " больше - " + loadSeconds + " сек. Удаляем профиль, т.к. возможны проблемы с его загрузкой в дальнейшем...", true);
895 System.IO.File.Delete(project.Variables["Login"].Value);
896 }
897
898 }catch{
899
900 project.SendWarningToLog("Нет профилей подходящих для работы!", true);
901 if (project.Variables["cfg_auto_walk"].Value!="True") throw new Exception("Завершили работу из за отсутствия профилей");
902 project.SendWarningToLog("Переходим в режим нагуливания", true);
903 project.Variables["profile_walk"].Value="Да";
904 }
905
906 CheckMobile();
907
908 if (CommonData.Debug) project.SendWarningToLog("GetProfile: завершение метода (debug)", true);
909
910 }
911
912 public void CloseAllTabs() {
913 while(instance.AllTabs.Count()>1){
914 instance.AllTabs[1].Close();
915 }
916 }
917
918 //методы тут
919
920// public void SiteInfoDownload(){
921
922// Tab tab = instance.ActiveTab();
923// Random rnd = new Random();
924
925// //File.Copy()
926
927// IZennoList SitesLst = project.Lists["SitesLst"];
928// string SiteInWork = SitesLst[0];
929
930// project.SendInfoToLog("Заходим на сайт - " + SiteInWork,true);
931// tab.NavigateWithCheck(SitesLst, DateTime.Now, 60, "");
932// tab.WaitDownloading();
933// System.Threading.Thread.Sleep(rnd.Next(2500,4500));
934
935// if(instance.ActiveTab.URL.Contains(SiteInWork)){
936// project.SendInfoToLog("Сайт загрузился, продолжаем работу с ним",true);
937// }else{
938// project.SendWarningToLog("Не удалось загрузить сайт",true);
939// }
940
941// List<string> MenuHrefBlocks = new List<string>();
942
943// HtmlElementCollection MenuBlocks = tab.FindElementsByXPath("//div[contains(@class, 'menu_top_block')]//ul[contains(@class, 'menu dropdown')]/li/a");
944
945// project.SendInfoToLog("Проверяем количество элементов меню.",true);
946// project.SendInfoToLog("Элементов меню найдено - " + MenuBlocks.Count,true);
947
948// for(int i=0;MenuBlocks.Count;i++){
949
950// List<HtmlElement> parents = instance.ActiveTab.FindElementsByXPath("//div[contains(@class, 'menu_top_block')]/ul").ToList();
951
952// foreach(HtmlElement parent in parents){
953
954// string MenuLink = parent.FindChildByXPath(".//div[contains(@class, 'menu_top_block')]//ul[contains(@class, 'menu dropdown')]/li/a", 0).GetAttribute("href");
955// project.SendInfoToLog("Добавляем ссылку на категорию меню во внутренний список - " + MenuLink,true);
956
957// MenuHrefBlocks.Add(MenuLink);
958// }
959// }
960
961// //Парсим все товары, что есть на сайте и скидываем в таблицу
962// for(int o;o<=MenuHrefBlocks.Count;o++){
963
964// string CatCheck = MenuHrefBlocks[0];
965// MenuHrefBlocks.RemoveAt(0);
966
967// tab.NavigateWithCheck(CatCheck, DateTime.Now, 60, "");
968// tab.WaitDownloading();
969// System.Threading.Thread.Sleep(rnd.Next(4500,8500));
970
971// List<HtmlElement> parents = instance.ActiveTab.FindElementsByXPath("//div[contains(@class, 'inner_wrap')]").ToList();
972
973// //Собираем все данные по товарам в категории
974// foreach(HtmlElement parent in parents){
975
976// string Name = parent.FindChildByXPath(".//div[contains(@class, 'item-title')]/a",0).InnerText;
977// string Price = parent.FindChildByXPath(".//div[contains(@class, 'price_matrix_wrapper')]/div/span/span",0).InnerText;
978// string ImgPath = parent.FindChildByXPath(".//span[contains(@class, 'section-gallery-wrapper__item-nav')]//following-sibling::img",0).GetAttribute("src");
979
980// ZennoPoster.HttpGet(
981// ImgPath,
982// "",
983// "UTF-8",
984// ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.File,
985// 30000,
986// "",
987// "",
988// true,
989// 3,
990// new String[]{},
991// @"E:\Учредитель\17) Фриланс\Zeno\Клиентам\Александра\Data\",
992// true
993// );
994
995// ExcelPackage package = new ExcelPackage();
996// var ws = package.Workbook.Worksheets.Add("List1");
997
998
999
1000// }
1001
1002// }
1003// }
1004
1005 public void FileCheck(){
1006
1007 Random rnd = new Random();
1008
1009 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 1",true);
1010
1011 IZennoTable Report = project.Tables["Report"];
1012 IZennoTable ExportTable = project.Tables["ExportTable"];
1013 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 2",true);
1014 project.Variables["FileName"].Value = DateTime.Now.ToString("ddMMyyyy");
1015 project.SendInfoToLog("Имя файла - " + project.Variables["FileName"].Value,true);
1016 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 3",true);
1017 int DaysDel = Convert.ToInt32(project.Variables["TimeDelete"].Value);
1018 int ReportsClean = Convert.ToInt32(project.Variables["ReportsClean"].Value);
1019 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 3",true);
1020
1021 string sity_name = project.Variables["sity_name"].Value;
1022 string cat_name = project.Variables["cat_name"].Value;
1023 string AccLogin = project.Variables["AccLogin"].Value;
1024 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 4",true);
1025 string SystemPath = Path.Combine(project.Directory, "System", project.Variables["AccLogin"].Value, sity_name);
1026 string ReportsPath = Path.Combine(project.Directory, "Reports", project.Variables["AccLogin"].Value, sity_name);
1027 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 5",true);
1028 string ReportsPathCheck = Path.Combine(project.Directory, "Reports", project.Variables["AccLogin"].Value, sity_name, cat_name + ".xlsx");
1029 string SystemPathCheck = Path.Combine(project.Directory, "System", project.Variables["AccLogin"].Value, project.Variables["FileName"].Value + ".xlsx");
1030 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 6",true);
1031 string FileSystemDelPath = Path.Combine(project.Directory, "System", project.Variables["AccLogin"].Value);
1032 string FileReportsDelPath = Path.Combine(project.Directory, "Reports", project.Variables["AccLogin"].Value);
1033 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 7",true);
1034 Directory.CreateDirectory(SystemPath);
1035 Directory.CreateDirectory(ReportsPath);
1036 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 8",true);
1037 Report.Bind(ReportsPathCheck);
1038
1039 System.Threading.Thread.Sleep(9000);
1040 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 10",true);
1041 if(File.Exists(ReportsPathCheck)){
1042 project.SendInfoToLog("Файл отчета уже существует, пишем в него данные",true);
1043 }else{
1044 project.SendWarningToLog("Файл отчета, в папке - " + "'" + sity_name + "'" + " с именем отчета - " + "'" + cat_name + "'" + " отсутствует в папке с Reports, создаем новый, пишем в него данные",true);
1045 //Копируем blank в существующую директорию, если она еще не существует
1046 File.Copy(project.Directory + @"\Reports\blank.xlsx", ReportsPathCheck);
1047 }
1048 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 11",true);
1049 if(File.Exists(SystemPathCheck)){
1050 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 11_1",true);
1051 project.SendInfoToLog("Файл с именем - " + project.Variables["FileName"].Value + " уже существует",true);
1052 }else{
1053 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 11_2",true);
1054 File.Copy(project.Directory + @"\System\blank2.xlsx", SystemPathCheck);
1055 }
1056 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 12",true);
1057 //Не удалять файлы вообще, стоит 0
1058 if(ReportsClean==0){
1059 project.SendInfoToLog("Файлы в папке System удаляться не будут, установлен 0", true);
1060 }else{
1061 string[] FilesSystem = Directory.GetFiles(FileSystemDelPath);
1062 foreach (string filesystem in FilesSystem){
1063 FileInfo fisys = new FileInfo(filesystem);
1064 if (fisys.CreationTime < DateTime.Now.AddDays(-DaysDel)){
1065 project.SendWarningToLog("Файлы в папке System - устарели, удаляем все файлы, старше - " + DaysDel + " дней",true);
1066 fisys.Delete();
1067 }
1068 }
1069 }
1070 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 13",true);
1071
1072 if(DaysDel==0){
1073 project.SendInfoToLog("Файлы в папке Reports удаляться не будут, установлен 0", true);
1074 }else{
1075 string[] FilesReports = Directory.GetFiles(FileReportsDelPath);
1076 foreach (string filereport in FilesReports){
1077 FileInfo fireport = new FileInfo(filereport);
1078 if (fireport.CreationTime < DateTime.Now.AddDays(-ReportsClean)){
1079 project.SendWarningToLog("Файлы в папке Reports - устарели, удаляем все файлы, старше - " + ReportsClean + " дней",true);
1080 fireport.Delete();
1081 }
1082 }
1083 }
1084 if(CommonData.Debug) project.SendWarningToLog("FileCheck - 14",true);
1085 }
1086
1087 public void ParseYes(){
1088
1089 Tab tab = instance.ActiveTab;
1090 Random rnd = new Random();
1091
1092 bool parse_yes = Convert.ToBoolean(project.Variables["parse_yes"].Value);
1093 IZennoTable GoodsInCab = project.Tables["GoodsInCab"];
1094 IZennoTable OldFileTable = project.Tables["OldFileTable"];
1095
1096 string NamesList = project.Variables["NamesList"].Value;
1097 string GoodsPrice = project.Variables["GoodsPrice"].Value;
1098 string ViewsElms = project.Variables["ViewsElms"].Value;
1099 string TimesElms = project.Variables["TimesElms"].Value;
1100 string MnfElems = project.Variables["MnfElems"].Value;
1101 string ElmsStatus = project.Variables["ElmsStatus"].Value;
1102 string ElmsIdTxt = project.Variables["ElmsIdTxt"].Value;
1103 string ElmsUrlTxt = project.Variables["ElmsUrlTxt"].Value;
1104
1105 List<string> OldTableColumnLst = OldFileTable.GetColumn("A").ToList();
1106 project.SendInfoToLog("Строк с id в листе - " + OldTableColumnLst.Count, true);
1107
1108 if(parse_yes){
1109
1110 //Парсим все что есть в личном кабинете, кидаем в файл с именем текущей даты
1111 while(true){
1112
1113 //Проверяем сначала наличие товаров в личном кабинете, чтобы избежать повторной загрузки
1114 HtmlElementCollection AllGoodsInCabinet = instance.ActiveTab.FindElementsByXPath("//div[contains(@class, 'bull-item-content__content-wrapper')]");
1115
1116 project.SendInfoToLog("Нашли товаров в личном кабинете - " + AllGoodsInCabinet.Count,true);
1117
1118 foreach (HtmlElement parent in AllGoodsInCabinet){
1119 if(CommonData.Debug) project.SendWarningToLog("parent - 1",true);
1120 //Парсим наименования товаров в категории
1121 NamesList = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content')]//a[contains(@data-role, 'bulletin-link')]|.//div[contains(@class, 'bull-item-content__subject-container')]/div/a",0).InnerText;
1122 //Парсим цены
1123 GoodsPrice = parent.FindChildByXPath(".//span[contains(@class, 'price-per-quantity__price')]|.//div[contains(@class, 'price-block__price')]|.//span[contains(@class, 'price-block__price')]|.//div[contains(@class, 'price-block__final-price')]/div/span[1]",0).InnerText;
1124 //Парсим время размещения
1125 ViewsElms = parent.FindChildByXPath(".//span[contains(@class, 'nano-eye-text')]",0).InnerText;
1126 //Парсим имя продавцов
1127 TimesElms = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-info__value')]/div|.//div[contains(@class, 'bull-item-info__value')]",0).InnerText;
1128 //Парсим продавца
1129 MnfElems = parent.FindChildByXPath(".//div[contains(@class, 'ellipsis-text__left-side')]/span|.//div[contains(@class, 'bull-item-info__row')]/div/span",0).InnerText;
1130 HtmlElement ElmsUrl = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content__subject-container')]/a[contains(@href, '')]",0);
1131 HtmlElement ElmsId = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content__subject-container')]/a[contains(@name, '')]",0);
1132 ElmsStatus = "Актуально";
1133
1134 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 3",true);
1135
1136 ElmsIdTxt = ElmsId.GetAttribute("name");
1137 ElmsUrlTxt = ElmsUrl.GetAttribute("href");
1138
1139 if(CommonData.Debug) project.SendWarningToLog("parent: 9",true);
1140
1141 //Сохраняем спарсенную инфу
1142
1143 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 4",true);
1144
1145 GoodsInCab.ColSeparator = ";";
1146 project.SendInfoToLog("Артикул - " + ElmsIdTxt,true);
1147 project.SendInfoToLog("Текст - " + NamesList,true);
1148 project.SendInfoToLog("Цена - " + GoodsPrice,true);
1149 project.SendInfoToLog("Время - " + TimesElms,true);
1150 project.SendInfoToLog("Производитель - " + MnfElems,true);
1151 project.SendInfoToLog("Состояние - " + ElmsStatus,true);
1152 project.SendInfoToLog("Просмотры - " + ViewsElms,true);
1153 project.SendInfoToLog("Ссылка - " + ElmsUrlTxt,true);
1154
1155 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 5",true);
1156
1157 //System.Threading.Thread.Sleep(500);
1158
1159 if(OldFileTable.RowCount==0){
1160 project.SendWarningToLog("Не заполнена таблица за предыдущую дату, не возможно выполнить сравнение строк и определить какие строки являются новыми, какие нет",true);
1161 }
1162
1163 if(OldTableColumnLst.Contains(ElmsIdTxt)){
1164 //Если id из списка OldTableColumnLst совпадает с id из таблицы за сегодня, то пропускаем запись
1165 project.SendInfoToLog("Строка с таким id - " + ElmsIdTxt +" уже добавлена", true);
1166 }else{
1167 project.SendInfoToLog("Дописываем новую строку с id - " + ElmsIdTxt, true);
1168 GoodsInCab.AddRow(ElmsIdTxt + ";" + NamesList + ";" + GoodsPrice + ";" + TimesElms + ";" + MnfElems + ";" + ElmsStatus + ";" + ViewsElms + ";" + ElmsUrlTxt);
1169 }
1170
1171 if(String.IsNullOrWhiteSpace(ViewsElms)){
1172 ViewsElms = "0";
1173 }
1174
1175 if(CommonData.Debug) project.SendWarningToLog("parent: 11",true);
1176 }
1177 if(CommonData.Debug) project.SendWarningToLog("parent: 12",true);
1178 HtmlElement nextPage = instance.ActiveTab.FindElementByXPath("//a[contains(@class, 'nextpage')]", 0);
1179
1180 if(nextPage.IsVoid) break;
1181 nextPage.Click();
1182 instance.ActiveTab.WaitDownloading();
1183 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
1184 if(CommonData.Debug) project.SendWarningToLog("parent: 13",true);
1185 }
1186
1187 OldTableColumnLst.Clear();
1188
1189 if(CommonData.Debug) project.SendWarningToLog("parent: 13_1",true);
1190
1191 }
1192
1193 if(CommonData.Debug) project.SendWarningToLog("parent: 19",true);
1194 //После того как спарсили все что есть в личном кабинете, идем к таблице экспорта и берем с нее данные для изменения существующих объявлений. Сначала ждем пока пользователь изменит таблицу, как ему нужно
1195
1196 //Показываем форму-всплывашку пользователю для ввода смс
1197 System.Windows.Forms.Form F = new System.Windows.Forms.Form();
1198 F.Text = "Закройте это окно";
1199
1200 System.Windows.Forms.MessageBox.Show("Закройте это окно крестиком, когда в папке System, в таблице за текущую дату сделаны все нужные изменения. Работа шаблона продолжится в автомате.");
1201 }
1202
1203 public void ParseBlock(){
1204
1205 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - старт метода",true);
1206
1207 Tab tab = instance.ActiveTab;
1208 Random rnd = new Random();
1209
1210 //Определяем таблицу, куда будем складывать данные
1211 IZennoTable TableToWrite = project.Tables["Report"];
1212
1213 int NextNumber = 2;
1214 int i = 0;
1215 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 1",true);
1216 //Собираем коллекцию
1217 List<HtmlElement> parents = instance.ActiveTab.FindElementsByXPath("//div[@class='bull-item-content__content-wrapper']").ToList();
1218
1219 project.SendInfoToLog("Нашли плашек с товарами: " + parents.Count);
1220
1221 for(int n=0;n<=parents.Count;n++){
1222
1223 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 2",true);
1224
1225 foreach(HtmlElement parent in parents){
1226 //Парсим наименования товаров в категории
1227 string NamesList = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content')]//a[contains(@data-role, 'bulletin-link')]|.//div[contains(@class, 'bull-item-content__subject-container')]/div/a",0).InnerText;
1228 //Парсим цены
1229 string GoodsPrice = parent.FindChildByXPath(".//span[contains(@class, 'price-per-quantity__price')]|.//div[contains(@class, 'price-block__price')]|.//span[contains(@class, 'price-block__price')]|.//div[contains(@class, 'price-block__final-price')]/div/span[1]",0).InnerText;
1230 //Парсим время размещения
1231 string ViewsElms = parent.FindChildByXPath(".//span[contains(@class, 'nano-eye-text')]",0).InnerText;
1232 //Парсим имя продавцов
1233 string TimesElms = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-info__value')]/div|.//div[contains(@class, 'bull-item-info__value')]",0).InnerText;
1234 //Парсим продавца
1235 string MnfElems = parent.FindChildByXPath(".//div[contains(@class, 'ellipsis-text__left-side')]/span|.//div[contains(@class, 'bull-item-info__row')]/div/span",0).InnerText;
1236 HtmlElement ElmsUrl = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content__subject-container')]/a[contains(@href, '')]",0);
1237 HtmlElement ElmsId = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content__subject-container')]/a[contains(@name, '')]",0);
1238 string ElmsStatus = "Актуально";
1239
1240 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 3",true);
1241
1242 string ElmsIdTxt = ElmsId.GetAttribute("name");
1243 string ElmsUrlTxt = ElmsUrl.GetAttribute("href");
1244
1245 if(CommonData.Debug) project.SendWarningToLog("parent: 9",true);
1246
1247 i++;
1248 if(CommonData.Debug) project.SendWarningToLog("Значение i - " + i,true);
1249 //Сохраняем спарсенную инфу
1250
1251 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 4",true);
1252
1253 TableToWrite.ColSeparator = ";";
1254 project.SendInfoToLog("Артикул - " + ElmsIdTxt,true);
1255 project.SendInfoToLog("Текст - " + NamesList,true);
1256 project.SendInfoToLog("Цена - " + GoodsPrice,true);
1257 project.SendInfoToLog("Время - " + TimesElms,true);
1258 project.SendInfoToLog("Производитель - " + MnfElems,true);
1259 project.SendInfoToLog("Состояние - " + ElmsStatus,true);
1260 project.SendInfoToLog("Просмотры - " + ViewsElms,true);
1261 project.SendInfoToLog("Ссылка - " + ElmsUrlTxt,true);
1262
1263 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 5",true);
1264
1265 if(String.IsNullOrWhiteSpace(ViewsElms)){
1266 ViewsElms = "0";
1267 }
1268 TableToWrite.AddRow(ElmsIdTxt + ";" + NamesList + ";" + GoodsPrice + ";" + TimesElms + ";" + MnfElems + ";" + ElmsStatus + ";" + ViewsElms + ";" + ElmsUrlTxt);
1269 }
1270
1271 if(CommonData.Debug) project.SendWarningToLog("ParseBlock - 6",true);
1272
1273 //Перебираем страницы, если они есть
1274 NextNumber++;
1275 tab.WaitDownloading();
1276 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
1277 //---
1278 if(CommonData.Debug) project.SendWarningToLog("parent: 18",true);
1279 project.SendInfoToLog("Смотрим страницу № - " + NextNumber,true);
1280
1281 HtmlElement ArchiveOn = instance.ActiveTab.FindElementByXPath("//tr[contains(@class, 'archiveModeItems')]/td/table//following-sibling::p/a",0);
1282 string ArchiveTxt = ArchiveOn.GetAttribute("innertext");
1283
1284 if(ArchiveTxt.Contains("Смотрите все объявления в архиве")) break;
1285
1286 }
1287 }
1288
1289 public void ParseBlockExport(){
1290
1291 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - старт метода",true);
1292
1293 Tab tab = instance.ActiveTab;
1294 Random rnd = new Random();
1295
1296 string sity_name = project.Variables["sity_name"].Value;
1297 string cat_name = project.Variables["cat_name"].Value;
1298
1299 IZennoTable ExportTable = project.Tables["ExportTable"];
1300 //Определяем таблицу, куда будем складывать данные
1301 IZennoTable TableToWrite = project.Tables["Report"];
1302
1303 project.SendInfoToLog("Пишем в таблицу - " + project.Directory + @"\Reports\" + sity_name + @"\" + cat_name + ".xlsx",true);
1304
1305 int NextNumber = 2;
1306 int i = 0;
1307
1308 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 1",true);
1309
1310 //Переходим на страницу поиска в farpost
1311 project.SendInfoToLog("Выходим на страницу поиска в farpost",true);
1312 tab.NavigateWithCheck("https://www.farpost.ru", DateTime.Now, 60, "");
1313
1314 project.SendInfoToLog("Строк в таблице экспорта - " + ExportTable.RowCount,true);
1315
1316 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 2",true);
1317
1318 //Удаляем дубли из списка
1319 List<string> range = ExportTable.GetColumn("B").ToList();
1320
1321 IZennoList Duble = project.Lists["Duble"];
1322
1323 lock (SyncObjects.ListSyncer){
1324 Duble.AddRange(range);
1325 }
1326
1327 //Удаляем дубли
1328 lock(SyncObjects.ListSyncer){
1329 HashSet<string> hs = new HashSet<string>(project.Lists["Duble"]);
1330 project.Lists["Duble"].Clear();
1331 lock (SyncObjects.ListSyncer){
1332 project.Lists["Duble"].AddRange(hs);
1333 }
1334 }
1335
1336 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 3",true);
1337
1338 if(CommonData.Debug){
1339 for(int x=0;x<=project.Lists["Duble"].Count;x++){
1340 string Test = project.Lists["Duble"][0];
1341 project.SendWarningToLog(Test, true);
1342 }
1343 }
1344
1345 sity_name = project.Profile.Town;
1346 cat_name = Duble[0];
1347 project.SendInfoToLog("Имя категории - " + cat_name,true);
1348
1349 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 4",true);
1350
1351 string Category = project.Lists["Duble"][0];
1352 project.Lists["Duble"].RemoveAt(0);
1353
1354 //Поле для поиска
1355 tab.WaitDownloading();
1356 System.Threading.Thread.Sleep(rnd.Next(8500, 12800));
1357
1358 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 6",true);
1359
1360 HtmlElement SearchField = tab.FindElementByXPath("//input[contains(@id, 'search')]",0);
1361 tab.FullEmulationMouseMoveToHtmlElement(SearchField);
1362 tab.FullEmulationMouseClick("left","click");
1363 System.Threading.Thread.Sleep(rnd.Next(4500, 7800));
1364 tab.KeyEvent("a","press","ctrl");
1365 tab.WaitDownloading();
1366 System.Threading.Thread.Sleep(rnd.Next(4500, 7800));
1367 tab.KeyEvent("Delete","press","");
1368 tab.WaitDownloading();
1369 System.Threading.Thread.Sleep(rnd.Next(4500, 7800));
1370 instance.SendText(Category, rnd.Next(67,89));
1371 System.Threading.Thread.Sleep(rnd.Next(4500, 7800));
1372 tab.KeyEvent("Enter", "press", "");
1373 tab.WaitDownloading();
1374 System.Threading.Thread.Sleep(rnd.Next(4500, 7800));
1375
1376 PageScrollingToBottom();
1377
1378 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 7",true);
1379
1380 //Собираем коллекцию
1381 List<HtmlElement> parents = instance.ActiveTab.FindElementsByXPath("//tbody[contains(@class, 'native')]//div[@class='bull-item-content__content-wrapper']").ToList();
1382
1383 project.SendInfoToLog("Нашли плашек с товарами: " + parents.Count);
1384
1385 for(int n=0;n<=parents.Count;n++){
1386
1387 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 8",true);
1388
1389 foreach(HtmlElement parent in parents){
1390 //Парсим наименования товаров в категории
1391 string NamesList = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content')]//a[contains(@data-role, 'bulletin-link')]|.//div[contains(@class, 'bull-item-content__subject-container')]/div/a",0).InnerText;
1392 //Парсим цены
1393
1394 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 9",true);
1395
1396 string GoodsPrice = parent.FindChildByXPath(".//span[contains(@class, 'price-per-quantity__price')]|.//div[contains(@class, 'price-block__price')]|.//span[contains(@class, 'price-block__price')]|.//div[contains(@class, 'price-block__final-price')]/div/span[1]",0).InnerText;
1397 //Парсим время размещения
1398 string ViewsElms = parent.FindChildByXPath(".//span[contains(@class, 'nano-eye-text')]",0).InnerText;
1399
1400 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 10",true);
1401
1402 //Парсим имя продавцов
1403 string TimesElms = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-info__value')]/div|.//div[contains(@class, 'bull-item-info__value')]",0).InnerText;
1404 //Парсим продавца
1405 string MnfElems = parent.FindChildByXPath(".//div[contains(@class, 'ellipsis-text__left-side')]/span|.//div[contains(@class, 'bull-item-info__row')]/div/span",0).InnerText;
1406 HtmlElement ElmsUrl = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content__subject-container')]/a[contains(@href, '')]",0);
1407
1408 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 11",true);
1409
1410 HtmlElement ElmsId = parent.FindChildByXPath(".//div[contains(@class, 'bull-item-content__subject-container')]/a[contains(@name, '')]",0);
1411 string ElmsStatus = "Актуально";
1412
1413 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 12",true);
1414
1415 string ElmsIdTxt = ElmsId.GetAttribute("name");
1416 string ElmsUrlTxt = ElmsUrl.GetAttribute("href");
1417
1418 if(CommonData.Debug) project.SendWarningToLog("parent: 6",true);
1419
1420 i++;
1421 if(CommonData.Debug) project.SendWarningToLog("Значение i - " + i,true);
1422 //Сохраняем спарсенную инфу
1423
1424 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 13",true);
1425
1426 TableToWrite.ColSeparator = ";";
1427 project.SendInfoToLog("Артикул - " + ElmsIdTxt,true);
1428 project.SendInfoToLog("Текст - " + NamesList,true);
1429 project.SendInfoToLog("Цена - " + GoodsPrice,true);
1430 project.SendInfoToLog("Время - " + TimesElms,true);
1431 project.SendInfoToLog("Производитель - " + MnfElems,true);
1432 project.SendInfoToLog("Состояние - " + ElmsStatus,true);
1433 project.SendInfoToLog("Просмотры - " + ViewsElms,true);
1434 project.SendInfoToLog("Ссылка - " + ElmsUrlTxt,true);
1435
1436 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 15",true);
1437
1438 if(String.IsNullOrWhiteSpace(ViewsElms)){
1439 ViewsElms = "0";
1440 }
1441
1442 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 16",true);
1443 TableToWrite.AddRow(ElmsIdTxt + ";" + NamesList + ";" + GoodsPrice + ";" + TimesElms + ";" + MnfElems + ";" + ElmsStatus + ";" + ViewsElms + ";" + ElmsUrlTxt);
1444
1445 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 17",true);
1446 break;
1447
1448 }
1449
1450 //Перебираем страницы, если они есть
1451 NextNumber++;
1452 tab.WaitDownloading();
1453 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
1454 //---
1455 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 18",true);
1456 project.SendInfoToLog("Смотрим страницу № - " + NextNumber,true);
1457
1458 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 19",true);
1459
1460 HtmlElement ArchiveOn = instance.ActiveTab.FindElementByXPath("//tr[contains(@class, 'archiveModeItems')]/td/table//following-sibling::p/a",0);
1461 string ArchiveTxt = ArchiveOn.GetAttribute("innertext");
1462
1463 if(ArchiveTxt.Contains("Смотрите все объявления в архиве")) break;
1464
1465 if(Mobile){
1466 instance.ActiveTab.FullEmulationMouseWheel(0,rnd.Next(8000,12000));
1467 break;
1468 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 20",true);
1469 }
1470 if(CommonData.Debug) project.SendWarningToLog("ParseBlockExport - 21",true);
1471 }
1472 }
1473
1474 public void TextDel(){
1475 Tab tab = instance.ActiveTab;
1476 Random rnd = new Random();
1477
1478 instance.ActiveTab.KeyEvent("a", "press", "ctrl");
1479 instance.ActiveTab.KeyEvent("Delete", "press", "");
1480 instance.ActiveTab.WaitDownloading();
1481 System.Threading.Thread.Sleep(rnd.Next(2600,8900));
1482 }
1483
1484 public void PageScrollingToBottom(){
1485
1486 Tab tab = instance.ActiveTab;
1487 Random rnd = new Random();
1488
1489 //Вычисляем конец страницы
1490 Document doc = tab.MainDocument;
1491 int height = doc.Height;
1492 project.SendInfoToLog("Высота экрана - " + height);
1493
1494 int X = 0; //Точка одсчета
1495 int Y = height; //Координата по оси Y
1496
1497 while(true){
1498 //Прокрутка
1499 instance.ActiveTab.FullEmulationMouseWheel(0,height);
1500 tab.WaitDownloading();
1501
1502 //Положение мыши по оси Y
1503 int posY = instance.ActiveTab.FullEmulationMouseCurrentPosition.Y;
1504
1505 //Условие, когда положение мыши по оси Y больше точки отсчета, то скроллим дальше
1506 if(posY > X){
1507 X = posY;
1508 Y += height;
1509 }else{
1510 break;
1511 }
1512 }
1513 }
1514
1515 public void FarpostEnter(){
1516
1517 Tab tab = instance.ActiveTab;
1518 Random rnd = new Random();
1519
1520 project.SendInfoToLog("Заходим на farpost.ru",true);
1521 tab.NavigateWithCheck("https://www.farpost.ru", DateTime.Now, 60, "");
1522 tab.WaitDownloading();
1523 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1524 }
1525
1526 public void AdvsUpToTime(){
1527
1528 Tab tab = instance.ActiveTab;
1529 Random rnd = new Random();
1530
1531 bool AdvsUpByTime = Convert.ToBoolean(project.Variables["AdvsUpByTime"].Value);
1532 string WhatToDoAdv = project.Variables["WhatToDoAdv"].Value;
1533 IZennoTable GoodsInCab = project.Tables["GoodsInCab"];
1534 string HowToUp = project.Variables["HowToUp"].Value;
1535
1536 List<string> AllNamesInRow = new List<string>();
1537
1538 //Поднимаем нужные объявления по времени
1539 if(AdvsUpByTime){
1540
1541 for(int b=0;b<=GoodsInCab.RowCount;b++){
1542
1543 string IDupTime = GoodsInCab.GetCell("A",b);
1544 project.SendInfoToLog("ID - " + IDupTime,true);
1545 string TimeUpTime = GoodsInCab.GetCell("I",b);
1546 project.SendInfoToLog("Время - " + TimeUpTime,true);
1547
1548 AllNamesInRow = GoodsInCab.GetRow(b).ToList();
1549 GoodsInCab.DeleteRow(b);
1550
1551 string format = "dd.MM.yyyy H:mm:ss";
1552 DateTime TimeToUp = DateTime.ParseExact(TimeUpTime, format, CultureInfo.InvariantCulture);
1553 project.SendInfoToLog("Время поднятия объявления установлено на - " + TimeToUp,true);
1554
1555 //Обычное поднятие нужного объявления по времени, которое задал пользователь
1556 if(HowToUp=="Автоподнятие"){
1557 if(DateTime.Now<TimeToUp){
1558 project.SendWarningToLog("Сейчас - " + DateTime.Now + " время поднятия еще не наступило",true);
1559 }else{
1560 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/bulletin/service-configure?ids=" + IDupTime + "&applier=upBulletin", DateTime.Now, 60, "");
1561 instance.ActiveTab.WaitDownloading();
1562 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1563
1564 HtmlElement AlertMsg = tab.FindElementByXPath("//div[contains(@class, 'alert alert_r')]/p",0);
1565 string Msg = AlertMsg.GetAttribute("innertext");
1566
1567 if(Msg=="Вы не являетесь владельцем объявления"){
1568 project.SendWarningToLog("Возможно, вы пытаетесь поднять не свое объявление с ID - " + IDupTime + " такое объявление поднять невозможно. Действия по поднятию не будут сделаны.",true);
1569 }else if(Msg=="Объявление должно быть оплачено"){
1570 HtmlElement OneAdv = tab.FindElementByXPath("//div[contains(@class, 'bull-item-content__subject-container')]//a[contains(@name, '')]",0);
1571 tab.FullEmulationMouseMoveToHtmlElement(OneAdv);
1572 tab.FullEmulationMouseClick("left","click");
1573 tab.WaitDownloading();
1574 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1575
1576 //Выбираем что сделать с обхявлением - Приклеить или Поднять
1577 if(WhatToDoAdv=="Приклеиваем"){
1578 HtmlElement AdvUp = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card__head')]/a/div[contains(text(), 'Приклеить')]",0);
1579 tab.FullEmulationMouseMoveToHtmlElement(AdvUp);
1580 tab.FullEmulationMouseClick("left","click");
1581 tab.WaitDownloading();
1582 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1583 project.SendInfoToLog("Объявление с id - " + IDupTime + " приклеено",true);
1584 }else{
1585 HtmlElement AdvGlue = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card__head')]/a/div[contains(text(), 'Поднять')]",0);
1586 tab.FullEmulationMouseMoveToHtmlElement(AdvGlue);
1587 tab.FullEmulationMouseClick("left","click");
1588 tab.WaitDownloading();
1589 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1590 project.SendInfoToLog("Объявление с id - " + IDupTime + " поднятно",true);
1591 }
1592
1593 }else{
1594 HtmlElement AdvUpBtn = tab.FindElementByXPath("//button[contains(@type, 'submit')]",0);
1595 tab.FullEmulationMouseMoveToHtmlElement(AdvUpBtn);
1596 tab.FullEmulationMouseClick("left","click");
1597 tab.WaitDownloading();
1598 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1599 }
1600 }
1601 }else{
1602 //Поднятие объявления по дням
1603 //https://www.farpost.ru/bulletin/service-configure?ids=89452104&applier=upBulletin
1604 //https://www.farpost.ru/bulletin/service-configure?ids=89238850&applier=autoUpBulletin
1605 switch(project.Variables["DailyAdvUp"].Value){
1606 case "Раз в три дня":
1607 HtmlElement OnceAThreeDays = instance.ActiveTab.FindElementByXPath("//select[contains(@name, 'period')]/option[contains(text(), 'Раз в три дня')]",0);
1608 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(OnceAThreeDays);
1609 OnceAThreeDays.SetAttribute("selected","selected");
1610 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1611 break;
1612 case "Раз в неделю":
1613 HtmlElement OnceAWeek = instance.ActiveTab.FindElementByXPath("//select[contains(@name, 'period')]/option[contains(text(), 'Раз в неделю')]",0);
1614 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(OnceAWeek);
1615 OnceAWeek.SetAttribute("selected","selected");
1616 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1617 break;
1618 default:
1619 project.SendInfoToLog("По умолчанию выбрана опция 'Поднимать объявление каждый день' ",true);
1620 HtmlElement EveryDay = instance.ActiveTab.FindElementByXPath("//select[contains(@name, 'period')]/option[contains(text(), 'Каждый день')]",0);
1621 EveryDay.SetAttribute("selected","selected");
1622 System.Threading.Thread.Sleep(rnd.Next(4500, 6500));
1623 break;
1624 }
1625 }
1626 GoodsInCab.AddRow(AllNamesInRow);
1627 }
1628 }
1629 }
1630
1631 public void DelAdvs(){
1632
1633 Tab tab = instance.ActiveTab;
1634 Random rnd = new Random();
1635
1636 bool DeleteAdvs = Convert.ToBoolean(project.Variables["DeleteAdvs"].Value);
1637 IZennoTable GoodsInCab = project.Tables["GoodsInCab"];
1638
1639 if(DeleteAdvs){
1640
1641 //https://www.farpost.ru/bulletin/89344197/edit
1642 //https://www.farpost.ru/bulletin/service-configure?ids=89450482&applier=deleteBulletin
1643
1644 //Удаляем из ЛК все что осталось в таблице выгрузке из личного кабинета в папке System за текущую дату
1645 for(int m=0;m<=GoodsInCab.RowCount;m++){
1646 string IdForLk = GoodsInCab.GetCell("A",m);
1647
1648 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/bulletin/service-configure?ids=" + IdForLk + "&applier=deleteBulletin", DateTime.Now, 60, "");
1649 project.SendInfoToLog("Идем на удаление объявления - " + IdForLk,true);
1650
1651 if(String.IsNullOrWhiteSpace(IdForLk)){
1652 project.SendInfoToLog("Все неактуальные объявления - удалены",true);
1653 break;
1654 }
1655
1656 instance.ActiveTab.WaitDownloading();
1657
1658 HtmlElement DelAdv = instance.ActiveTab.FindElementByXPath("//button[contains(@type, 'submit')]",0);
1659 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(DelAdv);
1660 instance.ActiveTab.FullEmulationMouseClick("left","click");
1661 }
1662
1663 project.SendInfoToLog("Переходим на страницу со всеми объявлениями в ЛК",true);
1664 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/personal/all/bulletins", DateTime.Now, 60, "");
1665 instance.ActiveTab.WaitDownloading();
1666 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1667 }
1668 }
1669
1670 public void FarpostJob(){
1671
1672 Tab tab = instance.ActiveTab;
1673 Random rnd = new Random();
1674
1675 if(CommonData.Debug) project.SendWarningToLog("FarpostJob - старт метода",true);
1676
1677 bool table_only = Convert.ToBoolean(project.Variables["table_only"].Value);
1678 bool sity_scan = Convert.ToBoolean(project.Variables["sity_scan"].Value);
1679 bool parse_yes = Convert.ToBoolean(project.Variables["parse_yes"].Value);
1680 if(CommonData.Debug) project.SendWarningToLog("FarpostJob - 1",true);
1681 bool scan_one = Convert.ToBoolean(project.Variables["scan_one"].Value);
1682 bool table_scan = Convert.ToBoolean(project.Variables["table_scan"].Value);
1683 if(CommonData.Debug) project.SendWarningToLog("FarpostJob - 2",true);
1684 bool sity_scan_once = Convert.ToBoolean(project.Variables["sity_scan_once"].Value);
1685 bool same_goods = Convert.ToBoolean(project.Variables["same_goods"].Value);
1686 if(CommonData.Debug) project.SendWarningToLog("FarpostJob - 3",true);
1687 bool new_goods_upload = Convert.ToBoolean(project.Variables["new_goods_upload"].Value);
1688 bool ParseWithTable = Convert.ToBoolean(project.Variables["ParseWithTable"].Value);
1689 if(CommonData.Debug) project.SendWarningToLog("FarpostJob - 4",true);
1690 bool AdvsUpByTime = Convert.ToBoolean(project.Variables["AdvsUpByTime"].Value);
1691 if(CommonData.Debug) project.SendWarningToLog("FarpostJob - 4_1",true);
1692 bool ChangeAdvOnly = Convert.ToBoolean(project.Variables["ChangeAdvOnly"].Value);
1693 if(CommonData.Debug) project.SendWarningToLog("FarpostJob - 5",true);
1694 bool TableOn = Convert.ToBoolean(project.Variables["TableOn"].Value);
1695 string HowToUp = project.Variables["HowToUp"].Value;
1696 string sity_name = project.Variables["sity_name"].Value;
1697 string cat_name = project.Variables["cat_name"].Value;
1698 string report_table_path = project.Variables["report_table_path"].Value;
1699 string WhereUpload = project.Variables["WhereUpload"].Value;
1700 string AccLogin = project.Variables["AccLogin"].Value;
1701 string FileName = project.Variables["FileName"].Value;
1702
1703 string NamesList = project.Variables["NamesList"].Value;
1704 string GoodsPrice = project.Variables["GoodsPrice"].Value;
1705 string ViewsElms = project.Variables["ViewsElms"].Value;
1706 string TimesElms = project.Variables["TimesElms"].Value;
1707 string MnfElems = project.Variables["MnfElems"].Value;
1708 string ElmsStatus = project.Variables["ElmsStatus"].Value;
1709
1710 IZennoTable GoodsInCab = project.Tables["GoodsInCab"];
1711 IZennoTable ExportTable = project.Tables["ExportTable"];
1712 IZennoList acc_path = project.Lists["acc_path"];
1713 project.Variables["FileName"].Value = DateTime.Now.ToString("ddMMyyyy");
1714
1715 //Problem in that block
1716 //Вводим город из настроек
1717 if(table_only){
1718
1719 //заход на фарпост
1720 FarpostEnter();
1721
1722 //выбор города
1723 project.SendInfoToLog("Выбираем город",true);
1724 HtmlElement SityChange = tab.FindElementByXPath("//div//a[contains(@class, 'city-alert__action')][2]",0);
1725 if(Mobile){
1726 tab.Touch.SwipeIntoView(SityChange);
1727 tab.Touch.Touch(SityChange);
1728 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1729 }else{
1730 tab.FullEmulationMouseMoveToHtmlElement(SityChange);
1731 tab.FullEmulationMouseClick("left","click");
1732 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1733 }
1734
1735 if(CommonData.Debug) project.SendWarningToLog("Берем данные с настроек",true);
1736 //input[contains(@class, 'search')]|//div[contains(@class, 'cleaned-input')]/input|//div[contains(@id, 'search-input-container')]/input
1737 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
1738 HtmlElement SityEnter = tab.FindElementByXPath("//div[contains(@class, 'search-container')]/input",0);
1739
1740 if(Mobile){
1741 if(CommonData.Debug) project.SendWarningToLog("table_only: 1",true);
1742 tab.Touch.SwipeIntoView(SityEnter);
1743 tab.Touch.Touch(SityEnter);
1744 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1745 instance.SendText(sity_name, rnd.Next(67,89));
1746 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1747 if(CommonData.Debug) project.SendWarningToLog("table_only: 2",true);
1748 HtmlElement NeededSity = tab.FindElementByXPath(String.Format("//li[contains(@class, 'best-selected')]/a/span[contains(text(), '{0}')]", sity_name),0);
1749 if(!NeededSity.IsVoid){
1750 if(CommonData.Debug) project.SendWarningToLog("table_only, NeededSity: 3",true);
1751 tab.Touch.Touch(NeededSity);
1752 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1753 tab.WaitDownloading();
1754 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1755 }else{
1756 if(CommonData.Debug) project.SendWarningToLog("table_only, NeededSity: 4",true);
1757 project.SendWarningToLog("Город - " + sity_name + " не найден, либо введен не верно. Выбрана 'Вся Россия' ",true);
1758 HtmlElement AllCountry = tab.FindElementByXPath("//a[contains(@class, 'whole-country')]|//div[contains(@class, 'country-navigation')]//a[contains(@class, 'whole-country')]",0);
1759 tab.Touch.Touch(AllCountry);
1760 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1761 tab.WaitDownloading();
1762 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1763 }
1764 }else{
1765 if(CommonData.Debug) project.SendWarningToLog("table_only, SityEnter: 5",true);
1766 tab.FullEmulationMouseMoveToHtmlElement(SityEnter);
1767 tab.FullEmulationMouseClick("left","click");
1768 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1769 instance.SendText(sity_name, rnd.Next(57,89));
1770 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1771
1772 HtmlElement NeededSity = tab.FindElementByXPath(String.Format("//li[contains(@class, 'best-selected')]//span[contains(text(), '{0}')]", sity_name),0);
1773 if(!NeededSity.IsVoid){
1774 if(CommonData.Debug) project.SendWarningToLog("table_only, SityEnter: 6",true);
1775 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1776 tab.FullEmulationMouseMoveToHtmlElement(NeededSity);
1777 tab.FullEmulationMouseClick("left","click");
1778 tab.WaitDownloading();
1779 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1780 }else{
1781 if(CommonData.Debug) project.SendWarningToLog("table_only, SityEnter: 7",true);
1782 project.SendWarningToLog("Город - " + sity_name + " не найден, либо введен не верно. Выбрана 'Вся Россия' ",true);
1783 HtmlElement AllCountry = tab.FindElementByXPath("//a[contains(@class, 'whole-country')]",0);
1784 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1785 tab.FullEmulationMouseMoveToHtmlElement(AllCountry);
1786 tab.FullEmulationMouseClick("left","click");
1787 tab.WaitDownloading();
1788 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
1789 }
1790 }
1791 }else{
1792 if(CommonData.Debug) project.SendWarningToLog("Берем данные с таблицы - выгрузки",true);
1793
1794 project.SendInfoToLog("Строка в таблице экспорта - " + ExportTable.RowCount,true);
1795
1796 //Логинимся на farpost
1797 FarpostEnter();
1798
1799 //Проверка на логин
1800 HtmlElement EnterLoginBtn = instance.ActiveTab.FindElementByXPath("//td[contains(@class, 'col_login')]/noindex/a",0);
1801 string InnertextBtn = EnterLoginBtn.GetAttribute("innertext");
1802 project.SendInfoToLog("Проверка залогинен ли уже аккаунт - " + InnertextBtn,true);
1803
1804 if(!String.IsNullOrWhiteSpace(InnertextBtn)){
1805 project.SendInfoToLog("Аккаунт не залогинен, заходим в ЛК",true);
1806
1807 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1808 HtmlElement LoginBtn = instance.ActiveTab.FindElementByXPath("//td[contains(@class, 'col_login')]//a|//button[contains(@class, 'bzr-nav-bar__button-item')]/i[contains(@class, 'bzr-main-sprite-icon_burger')]",0);
1809
1810 if(Mobile){
1811 project.SendInfoToLog("Нажимаем на меню-пирожок",true);
1812 instance.ActiveTab.Touch.SwipeIntoView(LoginBtn);
1813 instance.ActiveTab.Touch.Touch(LoginBtn);
1814 instance.ActiveTab.WaitDownloading();
1815 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1816 }else{
1817 project.SendInfoToLog("Кликаем на кнопку 'Войти' ",true);
1818 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(LoginBtn);
1819 instance.ActiveTab.FullEmulationMouseClick("left","click");
1820 instance.ActiveTab.WaitDownloading();
1821 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1822 }
1823
1824 if(Mobile){
1825 //Проверяем нужно ли нажимать на меню-пирожок
1826 project.SendInfoToLog("Нажимаем на кнопку 'Войти' в меню-пирожке",true);
1827 HtmlElement CakeMenu = instance.ActiveTab.FindElementByXPath("//a[contains(text(), 'Войти')]",0);
1828 instance.ActiveTab.Touch.SwipeIntoView(CakeMenu);
1829 instance.ActiveTab.Touch.Touch(CakeMenu);
1830 instance.ActiveTab.WaitDownloading();
1831 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1832 }
1833
1834 if(CommonData.Debug) project.SendWarningToLog("Login - 1",true);
1835
1836 IZennoList AccData = project.Lists["acc_path"];
1837 lock (SyncObjects.ListSyncer){
1838 string AccString = AccData[0];
1839 project.SendInfoToLog("Берем строку с данными из списка с аккаунтами - " + AccString,true);
1840 AccData.RemoveAt(0);
1841 AccData.Add(AccString);
1842
1843 if(CommonData.Debug) project.SendWarningToLog("Login - 2",true);
1844
1845 //Разбираем строку на переменные
1846 string[] AccDataList = AccString.Split(new char[]{';'});
1847
1848 project.Variables["AccLogin"].Value = AccDataList[0];
1849 project.SendInfoToLog("Имя - " + project.Variables["AccLogin"].Value,true);
1850 project.Variables["AccPass"].Value = AccDataList[1];
1851 project.SendInfoToLog("Пароль - " + project.Variables["AccPass"].Value,true);
1852 string SityForJob = AccDataList[2];
1853 project.SendInfoToLog("Город для работы - " + SityForJob,true);
1854
1855 }
1856
1857 if(CommonData.Debug) project.SendWarningToLog("Login - 3",true);
1858
1859 //Открываем форму ввода логина и пароля
1860 HtmlElement LoginForm = instance.ActiveTab.FindElementByXPath("//input[contains(@name, 'sign')]",0);
1861 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(LoginForm);
1862 instance.ActiveTab.FullEmulationMouseClick("left","click");
1863 project.SendInfoToLog("Вводим логин",true);
1864 instance.SendText(project.Variables["AccLogin"].Value, rnd.Next(67,89));
1865 instance.ActiveTab.WaitDownloading();
1866 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1867 //---
1868 HtmlElement PassForm = instance.ActiveTab.FindElementByXPath("//input[contains(@name, 'password')]",0);
1869 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(PassForm);
1870 instance.ActiveTab.FullEmulationMouseClick("left","click");
1871 project.SendInfoToLog("Вводим пароль",true);
1872 instance.SendText(project.Variables["AccPass"].Value, rnd.Next(67,89));
1873 instance.ActiveTab.WaitDownloading();
1874 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1875 //---
1876 HtmlElement EnterBtn = instance.ActiveTab.FindElementByXPath("//button[contains(@type, 'submit')]",0);
1877 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(EnterBtn);
1878 project.SendInfoToLog("Жмем кнопку входа",true);
1879 instance.ActiveTab.FullEmulationMouseClick("left","click");
1880 instance.ActiveTab.WaitDownloading();
1881 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1882 //---
1883 HtmlElement SmsBtn = instance.ActiveTab.FindElementByXPath("//button[contains(@type, 'submit')]",0);
1884
1885 if(!SmsBtn.IsVoid){
1886
1887 project.SendInfoToLog("Нашли кнопку для отправки смс, необходимо ввести смс, полученное на ваш телефон. После ввода, закройте форму крестиком. Смс отправится автоматом",true);
1888 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(SmsBtn);
1889 instance.ActiveTab.FullEmulationMouseClick("left","click");
1890 instance.ActiveTab.WaitDownloading();
1891 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1892
1893 //Показываем форму-всплывашку пользователю для ввода смс
1894 System.Windows.Forms.Form F = new System.Windows.Forms.Form();
1895 F.Text = "Введите смс полученное на телефон";
1896
1897 //создаем текстбокс
1898 System.Windows.Forms.TextBox textb = new System.Windows.Forms.TextBox();
1899 //указываем местоположение
1900 textb.Location = new System.Drawing.Point(40,50);
1901 // добавляем его на форму
1902 F.Controls.Add(textb);
1903
1904 F.ShowDialog();
1905
1906 //говорим в какую переменную положить
1907 project.Variables["test"].Value = textb.Text;
1908 //или возвращаем в переменную по умолчанию
1909 //return textb.Text;
1910 instance.SendText(project.Variables["test"].Value, rnd.Next(67,89));
1911
1912 //Вбиваем смс в поле
1913 HtmlElement SendSmsField = instance.ActiveTab.FindElementByXPath("//input[contains(@id, 'code')]",0);
1914 tab.FullEmulationMouseMoveToHtmlElement(SendSmsField);
1915 instance.ActiveTab.FullEmulationMouseClick("left","click");
1916 instance.ActiveTab.WaitDownloading();
1917 instance.SendText(project.Variables["test"].Value, rnd.Next(56, 89));
1918 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1919
1920 HtmlElement SendSmsBtn = instance.ActiveTab.FindElementByXPath("//button[contains(@type, 'submit')]",0);
1921 tab.FullEmulationMouseMoveToHtmlElement(SendSmsBtn);
1922 instance.ActiveTab.FullEmulationMouseClick("left","click");
1923 instance.ActiveTab.WaitDownloading();
1924 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1925 }
1926
1927 if(CommonData.Debug) project.SendWarningToLog("CitySelect - 1",true);
1928
1929 //Установка города для которого работает аккаунт
1930 HtmlElement CitySelect = instance.ActiveTab.FindElementByXPath("//a[contains(@id, 'cityNavigator')]",0);
1931
1932 if(!CitySelect.IsVoid){
1933 tab.FullEmulationMouseMoveToHtmlElement(CitySelect);
1934 instance.ActiveTab.FullEmulationMouseClick("left","click");
1935 instance.ActiveTab.WaitDownloading();
1936 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1937
1938 if(CommonData.Debug) project.SendWarningToLog("CitySelect - 2",true);
1939
1940 //Вводим нужный город
1941 HtmlElement SityEnter = instance.ActiveTab.FindElementByXPath("//input[contains(@class, 'search')]",0);
1942 tab.FullEmulationMouseMoveToHtmlElement(SityEnter);
1943 instance.ActiveTab.FullEmulationMouseClick("left","click");
1944 instance.ActiveTab.WaitDownloading();
1945 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1946 instance.SendText(sity_name, 67);
1947 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1948 tab.KeyEvent("a", "press", "ctrl");
1949 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1950 tab.KeyEvent("Delete", "press", "");
1951 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1952
1953 if(CommonData.Debug) project.SendWarningToLog("CitySelect - 3",true);
1954
1955 //Выбираем город
1956 HtmlElement SityChange = instance.ActiveTab.FindElementByXPath("//li[contains(@class, 'best-selected')]/a/span[contains(text(), '')]",0);
1957 tab.FullEmulationMouseMoveToHtmlElement(SityChange);
1958 instance.ActiveTab.FullEmulationMouseClick("left","click");
1959 instance.ActiveTab.WaitDownloading();
1960 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
1961 project.SendInfoToLog("Город - " + sity_name + " установлен",true);
1962 }
1963 }
1964
1965 for(int x=0;x<=ExportTable.RowCount;x++){
1966
1967 if(WhereUpload=="Битрикс"){
1968
1969 //lock(SyncObjects.TableSyncer){
1970
1971// string Status = ExportTable.GetCell("F", x);
1972
1973// //Проверяем статус строки - акутально или в работе
1974// for(int rowNum=0;rowNum<=ExportTable.RowCount;rowNum++){
1975// if(Status=="Актуально"){
1976// ExportTable.SetCell("F", x, "В работе");
1977// rowNum=x;
1978// break;
1979// }
1980// }
1981
1982 //Взяли одну строку с Export таблицы
1983 string ID = ExportTable.GetCell("A",x);
1984 project.SendInfoToLog("ID - " + ID,true);
1985 string Category = ExportTable.GetCell("B",x);
1986 project.SendInfoToLog("Категория - " + Category,true);
1987 string Name = ExportTable.GetCell("C",x);
1988 project.SendInfoToLog("Наименование товара - " + Name,true);
1989 string Price = ExportTable.GetCell("D",x);
1990 project.SendInfoToLog("Цена товара - " + Price,true);
1991 string Description = ExportTable.GetCell("E",x);
1992 project.SendInfoToLog("Описание товара - " + Description,true);
1993 string UpTime = ExportTable.GetCell("F", x);
1994 project.SendInfoToLog("Время поднятия объявления - " + UpTime,true);
1995 //Парсим описание, без спец символов
1996 //new Regex(@"(?<=text-align:\ justify;"">)[\w\W]*?(?=<br>)").Match(Description).Value;
1997 project.Variables["NewDescription"].Value = Regex.Replace(Description, @"<(.|\n)*?>", string.Empty);
1998 project.SendInfoToLog("Строка описания товара, после обработки - " + project.Variables["NewDescription"].Value,true);
1999 //}
2000 }else{
2001 //lock(SyncObjects.TableSyncer){
2002
2003// string Status = ExportTable.GetCell("F", x);
2004
2005// //Проверяем статус строки - акутально или в работе
2006// for(int rowNum=0;rowNum<=ExportTable.RowCount;rowNum++){
2007// if(Status=="Актуально"){
2008// ExportTable.SetCell("F", x, "В работе");
2009// rowNum=x;
2010// break;
2011// }
2012// }
2013
2014 string Name = ExportTable.GetCell("D",x);
2015 project.SendInfoToLog("Наименование - " + Name,true);
2016 string Price = ExportTable.GetCell("F",x);
2017 project.SendInfoToLog("Цена - " + Price,true);
2018 string UpTime = ExportTable.GetCell("G", x);
2019 project.SendInfoToLog("Время поднятия объявления - " + UpTime,true);
2020 //}
2021 }
2022
2023 //Парсим все что есть в личном кабинете для работы с таблицей GoodsInCab
2024
2025 project.SendInfoToLog("Переходим на страницу со всеми объявлениями в ЛК",true);
2026 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/personal/all/bulletins", DateTime.Now, 60, "");
2027 instance.ActiveTab.WaitDownloading();
2028 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2029
2030 if(String.IsNullOrWhiteSpace(project.Variables["AccLogin"].Value)){
2031
2032 IZennoList AccData = project.Lists["acc_path"];
2033
2034 lock (SyncObjects.ListSyncer){
2035 string AccString = AccData[0];
2036 project.SendInfoToLog("Берем строку с данными из списка с аккаунтами - " + AccString,true);
2037 AccData.RemoveAt(0);
2038 AccData.Add(AccString);
2039
2040 //Разбираем строку на переменные
2041 string[] AccDataList = AccString.Split(new char[]{';'});
2042
2043 project.Variables["AccLogin"].Value = AccDataList[0];
2044 project.SendInfoToLog("Имя - " + project.Variables["AccLogin"].Value,true);
2045 string AccPass = AccDataList[1];
2046 project.SendInfoToLog("Пароль - " + AccPass,true);
2047 }
2048
2049 System.Threading.Thread.Sleep(5000);
2050
2051 }
2052
2053 FileCheck();
2054
2055 if(CommonData.Debug) project.SendWarningToLog("AccDataList - 1",true);
2056
2057 //Указываем явный путь к файлу, куда нужно привязать таблицу и сохранить данные
2058
2059 string path = Path.Combine(project.Directory, "System", project.Variables["AccLogin"].Value, project.Variables["FileName"].Value + ".xlsx");
2060
2061 project.SendInfoToLog("Путь для записи в таблицу - " + path);
2062
2063 //instance.WaitForUserAction(5);
2064
2065 if(CommonData.Debug) project.SendWarningToLog("path - 1",true);
2066
2067 GoodsInCab.Bind(path);
2068
2069 //Переносим данные из таблицы за предыдущюю дату на текущую
2070 //Определяем дату на 1 день назад
2071
2072 IZennoTable OldFileTable = project.Tables["OldFileTable"];
2073
2074 if(CommonData.Debug) project.SendWarningToLog("OldFileTable - 1",true);
2075
2076 DateTime exp = DateTime.Now;
2077 exp = exp.AddDays(-1);
2078 project.Variables["OldFileName"].Value = exp.ToString(@"ddMMyyyy");
2079 project.SendInfoToLog("Имя файла за вчерашний день - " + project.Variables["OldFileName"].Value);
2080
2081 System.Threading.Thread.Sleep(5000);
2082 //instance.WaitForUserAction(50);
2083
2084 //Путь к файлу за предыдущий день
2085 string PathToOldFile = Path.Combine(project.Directory, "System", project.Variables["AccLogin"].Value, project.Variables["OldFileName"].Value + ".xlsx");
2086 string PathToNewFile = Path.Combine(project.Directory, "System", project.Variables["AccLogin"].Value, project.Variables["FileName"].Value + ".xlsx");
2087 string PathToToBackup = Path.Combine(project.Directory, "System", "Backup", project.Variables["FileName"].Value + ".xlsx");
2088
2089 if(CommonData.Debug) project.SendWarningToLog("OldFileTable - 2",true);
2090
2091 OldFileTable.Bind(PathToOldFile);
2092
2093 if(CommonData.Debug) project.SendWarningToLog("OldFileTable - 3",true);
2094
2095 System.Threading.Thread.Sleep(5000);
2096
2097 //instance.WaitForUserAction(50);
2098
2099 //Проверка - заполнена ли таблица за вчерашний день.
2100 //Заполнена - просто копируем на сегодня
2101 //File.Copy(PathToOldFile, PathToNewFile, true);
2102
2103 for(int y=0;y<=OldFileTable.RowCount;y++){
2104
2105 project.SendInfoToLog("Пишем строку № - " + y, true);
2106
2107 string id = OldFileTable.GetCell("A",y);
2108 string Name = OldFileTable.GetCell("B",y);
2109 string Price = OldFileTable.GetCell("C",y);
2110 string Time = OldFileTable.GetCell("D",y);
2111 string Manuf = OldFileTable.GetCell("E",y);
2112 string Status = OldFileTable.GetCell("F",y);
2113 string Views = OldFileTable.GetCell("G",y);
2114 string Link = OldFileTable.GetCell("H",y);
2115 string TimeOn = OldFileTable.GetCell("I",y);
2116
2117// if(TimeOn.Contains("1899")){
2118// if(CommonData.Debug) project.SendWarningToLog("OldFileTable - 3_1",true);
2119// string NewTimeOn = new Regex(@"(?<=1899\ ).*").Match(TimeOn).Value;
2120// TimeOn = project.Variables["NewTimeOn"].Value;
2121// }
2122
2123 string TimeOff = OldFileTable.GetCell("J",y);
2124 string Action = OldFileTable.GetCell("K",y);
2125 string OrderOn = OldFileTable.GetCell("L",y);
2126 string OrderOff = OldFileTable.GetCell("M",y);
2127 string PriceFirstPlace = OldFileTable.GetCell("N",y);
2128 string PriceFirstPage = OldFileTable.GetCell("O",y);
2129 string Archive = OldFileTable.GetCell("P",y);
2130 string InOrder = OldFileTable.GetCell("Q",y);
2131
2132 //Записываем данные в новую таблицу
2133 GoodsInCab.SetCell("A", y, id);
2134 GoodsInCab.SetCell("B", y, Name);
2135 GoodsInCab.SetCell("C", y, Price);
2136 GoodsInCab.SetCell("D", y, Time);
2137 GoodsInCab.SetCell("E", y, Manuf);
2138 GoodsInCab.SetCell("F", y, Status);
2139 GoodsInCab.SetCell("G", y, Views);
2140 GoodsInCab.SetCell("H", y, Link);
2141 GoodsInCab.SetCell("I", y, TimeOn);
2142 GoodsInCab.SetCell("J", y, TimeOff);
2143 GoodsInCab.SetCell("K", y, Action);
2144 GoodsInCab.SetCell("L", y, OrderOn);
2145 GoodsInCab.SetCell("M", y, OrderOff);
2146 GoodsInCab.SetCell("N", y, PriceFirstPlace);
2147 GoodsInCab.SetCell("O", y, PriceFirstPage);
2148 GoodsInCab.SetCell("P", y, Archive);
2149 GoodsInCab.SetCell("Q", y, InOrder);
2150 }
2151
2152 System.Threading.Thread.Sleep(5000);
2153
2154 ParseYes();
2155
2156 //F.ShowDialog();
2157
2158 //Используем настройки с таблицы, если включена опция
2159 if(TableOn){
2160 if(CommonData.Debug) project.SendWarningToLog("TableOn - 1",true);
2161
2162 string time_from = project.Variables["time_from"].Value;
2163 string time_to = project.Variables["time_to"].Value;
2164
2165 string Dt = "19:00:00";
2166 string dtFormat = "H:mm:ss";
2167 DateTime CheckTime = DateTime.ParseExact(Dt, dtFormat, CultureInfo.InvariantCulture);
2168
2169 if(CommonData.Debug) project.SendWarningToLog("TableOn - 2",true);
2170
2171 if(DateTime.Now>CheckTime){
2172 project.SendInfoToLog("Время - " + DateTime.Now + " выключать объявления",true);
2173 //instance.WaitForUserAction(10);
2174 goto TimeToOffAdvs;
2175 }else{
2176 project.SendInfoToLog("Не время снимать объявления - " + DateTime.Now,true);
2177 }
2178
2179 string TotalFormat = "H:mm:ss";
2180 DateTime StartJobTome = DateTime.ParseExact(time_from,TotalFormat,CultureInfo.InvariantCulture);
2181 project.SendInfoToLog("Время окончания работы шаблона установлено на - " + time_to + " ч.",true);
2182 DateTime StopJobTime = DateTime.ParseExact(time_to,TotalFormat,CultureInfo.InvariantCulture);
2183
2184 if(CommonData.Debug) project.SendWarningToLog("TableOn - 3",true);
2185
2186 project.SendInfoToLog("Включаем режим поднятия ставок.",true);
2187
2188 GoodsInCab.ColSeparator = ";";
2189
2190 if(CommonData.Debug) project.SendWarningToLog("TableOn - 4",true);
2191
2192 //Смотрим общее время
2193 while(DateTime.Now<StopJobTime){
2194
2195 //Остановка, по таймеру
2196 if(DateTime.Now>StopJobTime){
2197 throw new Exception("Остановили шаблон по таймингу. Сейчас - " + DateTime.Now);
2198 }
2199
2200 project.SendInfoToLog("Текущее время - " + DateTime.Now,true);
2201 project.SendInfoToLog("Строк в таблице- " + GoodsInCab.RowCount,true);
2202
2203 //instance.WaitForUserAction(50);
2204 System.Threading.Thread.Sleep(500);
2205
2206 for(int b=0;b<=GoodsInCab.RowCount;b++){
2207
2208 mutex.WaiteOne();
2209 //lock(SyncObjects.TableSyncer){
2210
2211 string Status = GoodsInCab.GetCell("F", b);
2212 project.SendInfoToLog("Status - " + Status,true);
2213 project.SendInfoToLog("b - " + b,true);
2214
2215 //Проверяем статус строки - акутально или в работе
2216 for(int rowNum=0;rowNum<=GoodsInCab.RowCount;rowNum++){
2217 project.SendInfoToLog("Проверяем статус объявления",true);
2218 if(Status=="Актуально"){
2219 project.SendInfoToLog("Ставим статус - 'Работаем'",true);
2220 GoodsInCab.SetCell("F", b, "Работаем");
2221 rowNum=b;
2222 break;
2223 }
2224 }
2225
2226 if(CommonData.Debug) project.SendWarningToLog("TableOn - 4_1",true);
2227 project.Variables["AdvLink"].Value = GoodsInCab.GetCell("H",b);
2228 project.SendInfoToLog(project.Variables["AdvLink"].Value,true);
2229 project.Variables["TimeOn"].Value = GoodsInCab.GetCell("I",b);
2230 project.SendInfoToLog(project.Variables["TimeOn"].Value,true);
2231 project.Variables["TimeOff"].Value = GoodsInCab.GetCell("J",b);
2232 project.SendInfoToLog(project.Variables["TimeOff"].Value,true);
2233 project.Variables["WhatToDo"].Value = GoodsInCab.GetCell("K",b);
2234 project.SendInfoToLog(project.Variables["WhatToDo"].Value,true);
2235 project.Variables["SetOn"].Value = GoodsInCab.GetCell("L",b);
2236 project.SendInfoToLog(project.Variables["SetOn"].Value,true);
2237 project.Variables["SetOff"].Value = GoodsInCab.GetCell("M",b);
2238 project.SendInfoToLog(project.Variables["SetOff"].Value,true);
2239 project.Variables["PriceForFirstPlace"].Value = GoodsInCab.GetCell("N",b);
2240 project.SendInfoToLog(project.Variables["PriceForFirstPlace"].Value,true);
2241 project.Variables["PriceForFirstPage"].Value = GoodsInCab.GetCell("O",b);
2242 project.SendInfoToLog(project.Variables["PriceForFirstPage"].Value,true);
2243 project.Variables["Archive"].Value = GoodsInCab.GetCell("P",b);
2244 project.SendInfoToLog(project.Variables["Archive"].Value,true);
2245 project.Variables["GoodsInSell"].Value = GoodsInCab.GetCell("Q",b);
2246 project.SendInfoToLog(project.Variables["GoodsInSell"].Value,true);
2247
2248 //Остановка, когда прошли все строки в таблице
2249 if(b==GoodsInCab.RowCount){
2250 throw new Exception("Обошли все объявления в таблице с которыми нужно было работать. Работа шаблона остановлена до наступления времени в расписании");
2251 }
2252 project.SendInfoToLog("Проверяем в таблице строку № - " + b,true);
2253 //instance.WaitForUserAction(500);
2254 System.Threading.Thread.Sleep(500);
2255
2256 mutex.ReleaseMutex();
2257 //}
2258
2259 //Если не заполнено 'время вкл' и 'время выкл', то пропускам строку
2260 if(String.IsNullOrWhiteSpace(project.Variables["TimeOn"].Value) | String.IsNullOrWhiteSpace(project.Variables["TimeOff"].Value)){
2261
2262 if(CommonData.Debug) project.SendWarningToLog("TableOn - 4_2",true);
2263
2264 project.SendWarningToLog("Не заполнено время работы с объявлением, пропускаем его.. Работаем с остальными",true);
2265 }else{
2266 //Сначала проверяем, заполнена ли строка "наличие". Проверка идет с нее
2267 if(String.IsNullOrWhiteSpace(project.Variables["GoodsInSell"].Value)){
2268 if(CommonData.Debug) project.SendWarningToLog("TableOn - 4_3",true);
2269 project.SendInfoToLog("Не заполнена строка 'наличие тов.?' - действий с объявлением " + project.Variables["AdvLink"].Value + " сделано не будет");
2270 }else{
2271
2272 if(project.Variables["TimeOn"].Value.Contains("1899")){
2273 if(CommonData.Debug) project.SendWarningToLog("OldFileTable - 3_1",true);
2274 project.Variables["NewTimeOn"].Value = new Regex(@"(?<=1899\ ).*").Match(project.Variables["TimeOn"].Value).Value;
2275 project.Variables["TimeOn"].Value = project.Variables["NewTimeOn"].Value;
2276 if(CommonData.Debug) project.SendWarningToLog("1899 -" + project.Variables["NewTimeOn"].Value,true);
2277 if(CommonData.Debug) project.SendWarningToLog("1899 -" + project.Variables["TimeOn"].Value,true);
2278 //instance.WaitForUserAction(10);
2279 }
2280 if(project.Variables["TimeOff"].Value.Contains("1899")){
2281 if(CommonData.Debug) project.SendWarningToLog("OldFileTable - 3_1",true);
2282 project.Variables["NewTimeOff"].Value = new Regex(@"(?<=1899\ ).*").Match(project.Variables["TimeOff"].Value).Value;
2283 project.Variables["TimeOff"].Value = project.Variables["NewTimeOff"].Value;
2284 if(CommonData.Debug) project.SendWarningToLog("1899 -" + project.Variables["NewTimeOff"].Value,true);
2285 if(CommonData.Debug) project.SendWarningToLog("1899 -" + project.Variables["TimeOff"].Value,true);
2286 //instance.WaitForUserAction(10);
2287 }
2288
2289 project.SendInfoToLog("Время включения - " + project.Variables["TimeOn"].Value,true);
2290 project.SendInfoToLog("Время выключения - " + project.Variables["TimeOff"].Value,true);
2291
2292 //instance.WaitForUserAction(10);
2293
2294 if(CommonData.Debug) project.SendWarningToLog("TableOn - 5",true);
2295 //Берем время включения dd.MM.yyyy
2296 string format = "H:mm:ss";
2297
2298 project.SendInfoToLog("Работаем с объявлением - " + project.Variables["AdvLink"].Value,true);
2299
2300 DateTime TimeToUp = DateTime.ParseExact(project.Variables["NewTimeOn"].Value, format, CultureInfo.InvariantCulture);
2301 project.SendInfoToLog("Время поднятия объявления установлено на - " + TimeToUp,true);
2302
2303 string OffFormat = "H:mm:ss";
2304
2305 DateTime TimeToOff = DateTime.ParseExact(project.Variables["NewTimeOff"].Value, OffFormat, CultureInfo.InvariantCulture);
2306 project.SendInfoToLog("Время снятия объявления установлено на - " + TimeToOff,true);
2307
2308 if(CommonData.Debug) project.SendWarningToLog("TableOn - 4_3",true);
2309
2310 if(DateTime.Now<TimeToUp){
2311 if(CommonData.Debug) project.SendWarningToLog("TableOn - 6",true);
2312 project.SendInfoToLog("Время работать с объявлением - " + project.Variables["AdvLink"].Value + " еще не наступило",true);
2313 project.SendInfoToLog("Сейчас - " + DateTime.Now,true);
2314 //instance.WaitForUserAction(20);
2315
2316 }else if(DateTime.Now>TimeToUp){
2317
2318 if(CommonData.Debug) project.SendWarningToLog("TableOn - 7",true);
2319 project.SendInfoToLog("Время - " + DateTime.Now + " работать с объвлением",true);
2320 //Если время наступил, то берем объявление в работу
2321
2322 //Проверяем - в архиве объявление или нет
2323 if(project.Variables["Archive"].Value=="нет"){
2324 project.SendInfoToLog("Объявлению - " + project.Variables["AdvLink"].Value + " присвоен статус 'в архиве', пропускаем его",true);
2325 }else if(project.Variables["GoodsInSell"].Value=="заказ"){
2326 project.SendInfoToLog("Объявлению - " + project.Variables["AdvLink"].Value + " присвоен статус 'заказ', пропускаем его",true);
2327 }else{
2328 project.SendWarningToLog("TableOn - 8",true);
2329
2330 //Если нужно вынуть, то берем его из архива и возвращаем на публикацию
2331 HtmlElement AdvInArchive = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'mod__negative')]",0);
2332 string ErrorMsg = AdvInArchive.GetAttribute("innertext");
2333
2334 if(String.IsNullOrWhiteSpace(ErrorMsg)){
2335 project.SendInfoToLog("Объявление уже размещено на сайте, возвращать из архива не нужно",true);
2336
2337 instance.ActiveTab.Navigate(project.Variables["AdvLink"].Value, "");
2338 instance.ActiveTab.WaitDownloading();
2339 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2340
2341 //Проверяем какое действие назначено объявлению в таблице
2342 if(String.IsNullOrWhiteSpace(project.Variables["WhatToDo"].Value)){
2343
2344 project.SendInfoToLog("Объявлению не назначено действие 'приклеить', ставим ставки 'как есть' из полей 'ставка вкл' и 'ставка выкл'",true);
2345 if(CommonData.Debug) project.SendWarningToLog("TableOn - 8",true);
2346
2347 System.Threading.Thread.Sleep(1000);
2348
2349 //Проверяем - приклеенно ли объявление?
2350 //Если объявление уже приклеено, то прибавляем с ставке за первое место 10 руб и поднимаем объявление
2351 //div[contains(@class, 'stick-form__applied-label')]
2352 HtmlElement AlredySticked = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card-head__link')]",0);
2353 //div[contains(@class, 'bulletin-user-action-items')]/a[contains(@class, 'serviceStick')]
2354 if(CommonData.Debug) project.SendWarningToLog("TableOn - 9",true);
2355 string Stiked = AlredySticked.GetAttribute("innertext");
2356
2357 //Если объявление не приклеено, то жмем "Приклеить"
2358 if(Stiked.Contains("Приклеить")){
2359
2360 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AlredySticked);
2361 instance.ActiveTab.WaitDownloading();
2362 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2363
2364 HtmlElement ChangeAdvGluePrice = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin-user-action-items')]/a[contains(@class, 'serviceStick')]",0);
2365 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(ChangeAdvGluePrice);
2366 instance.ActiveTab.FullEmulationMouseClick("left","click");
2367 instance.ActiveTab.WaitDownloading();
2368
2369 if(CommonData.Debug) project.SendWarningToLog("TableOn - 10",true);
2370 project.SendInfoToLog("Объявление не приклеено, изменяем ставку на ставку включения",true);
2371
2372 HtmlElement InputPrice = instance.ActiveTab.FindElementByXPath("//input[contains(@name, 'stickPrice')]",0);
2373 if(CommonData.Debug) project.SendWarningToLog("TableOn - 11",true);
2374
2375 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(InputPrice);
2376 instance.ActiveTab.FullEmulationMouseClick("left","click");
2377 System.Threading.Thread.Sleep(rnd.Next(200,1200));
2378 instance.ActiveTab.KeyEvent("a", "press", "ctrl");
2379 instance.ActiveTab.KeyEvent("Delete", "press", "");
2380 instance.ActiveTab.WaitDownloading();
2381 System.Threading.Thread.Sleep(rnd.Next(200,1200));
2382
2383 if(DateTime.Now>TimeToOff){
2384 instance.SendText(project.Variables["SetOff"].Value,67);
2385 }else{
2386 instance.SendText(project.Variables["SetOn"].Value,67);
2387 }
2388
2389 //Прожимаем Enter, чтобы сохранить изменения
2390 instance.ActiveTab.KeyEvent("Enter", "press", "");
2391 instance.ActiveTab.WaitDownloading();
2392 System.Threading.Thread.Sleep(rnd.Next(1500,2500));
2393
2394 if(CommonData.Debug) project.SendWarningToLog("TableOn - 12",true);
2395
2396 //Жмем кнопку "приклеить"
2397 HtmlElement StickFinal = instance.ActiveTab.FindElementByXPath("//button[contains(@type, 'submit')]",0);
2398 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(StickFinal);
2399 instance.ActiveTab.FullEmulationMouseClick("left","click");
2400 instance.ActiveTab.WaitDownloading();
2401 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2402
2403 }else{
2404
2405 HtmlElement StickClick = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'serviceStick')]",0);
2406 instance.ActiveTab.FullEmulationMouseMoveAboveHtmlElement(StickClick, 7);
2407 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2408
2409 instance.ActiveTab.WaitDownloading();
2410 System.Threading.Thread.Sleep(500);
2411
2412 HtmlElement ChangePrice = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card__actions')]/a",0);
2413 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(StickClick);
2414 instance.ActiveTab.FullEmulationMouseClick("left","click");
2415 System.Threading.Thread.Sleep(rnd.Next(500,2500));
2416
2417 //Работа с объявлением по приклеиванию на первое место:
2418
2419 project.SendInfoToLog("Вписываем ставку включения - " + project.Variables["SetOn"].Value,true);
2420 //Если не приклеено, то прибавляем к ставке 2 руб
2421
2422 HtmlElement InputPrice = instance.ActiveTab.FindElementByXPath("//input[contains(@name, 'stickPrice')]",0);
2423
2424 if(CommonData.Debug) project.SendWarningToLog("TableOn - 16",true);
2425
2426 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(InputPrice);
2427 instance.ActiveTab.FullEmulationMouseClick("left","click");
2428 System.Threading.Thread.Sleep(rnd.Next(500,2500));
2429 instance.ActiveTab.KeyEvent("a", "press", "ctrl");
2430 instance.ActiveTab.KeyEvent("Delete", "press", "");
2431 instance.ActiveTab.WaitDownloading();
2432 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2433
2434 if(DateTime.Now>TimeToOff){
2435 instance.SendText(project.Variables["SetOff"].Value,67);
2436 }else{
2437 instance.SendText(project.Variables["SetOn"].Value,67);
2438 }
2439 instance.ActiveTab.WaitDownloading();
2440 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2441
2442 //Прожимаем Enter, чтобы сохранить изменения
2443 instance.ActiveTab.KeyEvent("Enter", "press", "");
2444 instance.ActiveTab.WaitDownloading();
2445 System.Threading.Thread.Sleep(rnd.Next(1500,2500));
2446
2447 HtmlElement StickConfirm = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'applier-s-submit__confirm')]//button[contains(@type, 'submit')]",0);
2448 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(StickConfirm);
2449 instance.ActiveTab.FullEmulationMouseClick("left","click");
2450 System.Threading.Thread.Sleep(rnd.Next(1500,2000));
2451 }
2452
2453 }else if(project.Variables["WhatToDo"].Value=="приклеить"){
2454
2455 project.SendInfoToLog("Объявлению назначено действие 'приклеить', выполняем",true);
2456
2457 if(CommonData.Debug) project.SendWarningToLog("TableOn - 8",true);
2458
2459 //Работа с объявлением по приклеиванию на первое место:
2460
2461 //Если объявление уже приклеено, то прибавляем с ставке за первое место 10 руб и поднимаем объявление
2462 //div[contains(@class, 'stick-form__applied-label')]
2463 HtmlElement AlredySticked = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card-head__link')]",0);
2464 if(CommonData.Debug) project.SendWarningToLog("TableOn - 9",true);
2465 string Stiked = AlredySticked.GetAttribute("innertext");
2466
2467 if(!String.IsNullOrWhiteSpace(Stiked)){
2468
2469 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AlredySticked);
2470 instance.ActiveTab.WaitDownloading();
2471 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2472
2473 HtmlElement ChangeAdvGluePrice = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card__actions')]/a[contains(@class, 'bzr-btn_size_l')]",0);
2474 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(ChangeAdvGluePrice);
2475 instance.ActiveTab.FullEmulationMouseClick("left","click");
2476 instance.ActiveTab.WaitDownloading();
2477
2478 if(CommonData.Debug) project.SendWarningToLog("TableOn - 10",true);
2479 project.SendInfoToLog("Объявление уже приклеено, прибавляем к ставке за первое место 10 руб",true);
2480
2481 HtmlElement NowPriceForFirstPlace = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'stick-applier-steps__price-cell')]/a/span[contains(@data-role, 'price-value')]",0);
2482
2483 int NowPrice = Convert.ToInt32(NowPriceForFirstPlace.GetAttribute("innertext"));
2484 project.SendInfoToLog("Цена за первое место - " + NowPrice,true);
2485
2486 //int persent = NowPrice/100*2;
2487 //project.SendInfoToLog("Текущий процент - " + persent,true);
2488
2489 int NewPriceWithPersent = NowPrice + Convert.ToInt32(project.Variables["PriceForFirstPlace"].Value);
2490
2491 if(String.IsNullOrWhiteSpace(project.Variables["PriceForFirstPlace"].Value)){
2492 project.Variables["PriceForFirstPlace"].Value = "5";
2493 project.SendInfoToLog("Прибавляем к текущей цене 5 руб, получаем - " + NewPriceWithPersent + " ставим эту цену в качестве новой ставки",true);
2494 }else{
2495 project.SendInfoToLog("Прибавляем к текущей цене 10 руб, получаем - " + NewPriceWithPersent + " ставим эту цену в качестве новой ставки",true);
2496 }
2497
2498 HtmlElement InputPrice = instance.ActiveTab.FindElementByXPath("//input[contains(@name, 'stickPrice')]",0);
2499 if(CommonData.Debug) project.SendWarningToLog("TableOn - 11",true);
2500
2501 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(InputPrice);
2502 instance.ActiveTab.FullEmulationMouseClick("left","click");
2503 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2504 instance.ActiveTab.KeyEvent("a", "press", "ctrl");
2505 instance.ActiveTab.KeyEvent("Delete", "press", "");
2506 instance.ActiveTab.WaitDownloading();
2507 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2508 //Проверяем - заполнены ли ставки за первое место и первую страницу
2509 if(String.IsNullOrWhiteSpace(project.Variables["PriceForFirstPage"].Value) || String.IsNullOrWhiteSpace(project.Variables["PriceForFirstPlace"].Value)){
2510 project.SendInfoToLog("Не заполнено поле 'Ставка (1е место) или 'Ставка(1я стр)' - не трогаем ставки за первое места и первую страницу",true);
2511 instance.SendText(project.Variables["SetOn"].Value,67);
2512 instance.ActiveTab.WaitDownloading();
2513 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2514 }else{
2515 instance.SendText(Convert.ToString(NewPriceWithPersent),67);
2516 instance.ActiveTab.WaitDownloading();
2517 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2518 }
2519
2520 //Прожимаем Enter, чтобы сохранить изменения
2521 instance.ActiveTab.KeyEvent("Enter", "press", "");
2522 instance.ActiveTab.WaitDownloading();
2523 System.Threading.Thread.Sleep(rnd.Next(1500,2000));
2524
2525 if(CommonData.Debug) project.SendWarningToLog("TableOn - 12",true);
2526
2527 }else{
2528
2529 if(CommonData.Debug) project.SendWarningToLog("TableOn - 14",true);
2530
2531 project.SendInfoToLog("Объявление не приклеено, прибавляем к ставке за первое место 2 руб, затем приклеиваем",true);
2532 //Если не приклеено, то прибавляем к ставке 2 руб
2533 HtmlElement NowPriceForFirstPlace = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'stick-applier-steps__price-cell')]/a/span[contains(@data-role, 'price-value')]",0);
2534
2535 int NowPrice = Convert.ToInt32(NowPriceForFirstPlace.GetAttribute("innertext"));
2536 project.SendInfoToLog("Цена за первое место - " + NowPrice,true);
2537
2538 if(CommonData.Debug) project.SendWarningToLog("TableOn - 15",true);
2539
2540 //int persent = NowPrice/100*2;
2541 //project.SendInfoToLog("Текущий процент - " + persent,true);
2542
2543 int NewPriceWithPersent = NowPrice + Convert.ToInt32(project.Variables["PriceForFirstPlace"].Value);
2544 project.SendInfoToLog("Прибавляем к текущей цене 2 руб, получаем - " + NewPriceWithPersent + " ставим эту цену в качестве новой ставки",true);
2545 HtmlElement InputPrice = instance.ActiveTab.FindElementByXPath("//input[contains(@name, 'stickPrice')]",0);
2546
2547 if(CommonData.Debug) project.SendWarningToLog("TableOn - 16",true);
2548
2549 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(InputPrice);
2550 instance.ActiveTab.FullEmulationMouseClick("left","click");
2551 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2552 instance.ActiveTab.KeyEvent("a", "press", "ctrl");
2553 instance.ActiveTab.KeyEvent("Delete", "press", "");
2554 instance.ActiveTab.WaitDownloading();
2555 System.Threading.Thread.Sleep(rnd.Next(500,2500));
2556 //Проверяем - заполнены ли ставки за первое место и первую страницу
2557 if(String.IsNullOrWhiteSpace(project.Variables["PriceForFirstPage"].Value) || String.IsNullOrWhiteSpace(project.Variables["PriceForFirstPlace"].Value)){
2558 project.SendInfoToLog("Не заполнено поле 'Ставка (1е место) или 'Ставка(1я стр)' - не трогаем ставки за первое места и первую страницу",true);
2559 instance.SendText(project.Variables["SetOn"].Value,67);
2560 instance.ActiveTab.WaitDownloading();
2561 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2562 }else{
2563 instance.SendText(Convert.ToString(NewPriceWithPersent),67);
2564 instance.ActiveTab.WaitDownloading();
2565 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2566 }
2567
2568 //Прожимаем Enter, чтобы сохранить изменения
2569 instance.ActiveTab.KeyEvent("Enter", "press", "");
2570 instance.ActiveTab.WaitDownloading();
2571 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2572 }
2573 }
2574
2575 }else{
2576
2577 if(CommonData.Debug) project.SendWarningToLog("TableOn - 19",true);
2578
2579 project.SendInfoToLog("Возвращаем объявление из архива",true);
2580 HtmlElement BackAdv = instance.ActiveTab.FindElementByXPath("//a[contains(@class, 'doProlong')]",0);
2581 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(BackAdv);
2582 instance.ActiveTab.FullEmulationMouseClick("left","click");
2583 instance.ActiveTab.WaitDownloading();
2584 System.Threading.Thread.Sleep(rnd.Next(500,1500));
2585
2586 if(CommonData.Debug) project.SendWarningToLog("TableOn - 20",true);
2587 }
2588 }
2589 //Ставим ставки выключения и снимаем приклеенные объявления
2590 }
2591 }
2592 }
2593 }
2594 }
2595
2596 TimeToOffAdvs:
2597
2598 //Проверяем наличие таблицы за текущий день
2599 if(!File.Exists(PathToNewFile)){
2600 throw new Exception("Не удалось найти таблицу за текущий день. Работа шаблона остановлена");
2601 }
2602
2603 for(int h=0;h<=GoodsInCab.RowCount;h++){
2604
2605 //Остановка, когда прошли все строки в таблице
2606 if(h==GoodsInCab.RowCount){
2607 throw new Exception("Обошли все объявления в таблице с которыми нужно было работать. Работа шаблона остановлена до наступления времени в расписании");
2608 }
2609
2610 //lock(SyncObjects.TableSyncer){
2611
2612 string Status = GoodsInCab.GetCell("F", h);
2613 project.SendInfoToLog("Проверяем статус текущего объявления - 'Работаем' или 'Актуально' ?", true);
2614
2615 //Проверяем статус строки - актуально или в работе
2616 for(int rowNum=0;rowNum<=GoodsInCab.RowCount;rowNum++){
2617 project.SendInfoToLog("Идем по строке № - " + h);
2618 if(Status=="Актуально"){
2619 project.SendInfoToLog("Ставим статус - 'Работаем' текущему объявлению", true);
2620 GoodsInCab.SetCell("F", h, "Работаем");
2621 GoodsInCab.DeleteRow(h);
2622 rowNum=h;
2623 GoodsInCab.AddRow(project.Variables["ElmsIdTxt"].Value + ";" + project.Variables["NamesList"].Value + ";" + project.Variables["GoodsPrice"].Value + ";" + project.Variables["TimesElms"].Value + ";" + project.Variables["MnfElems"].Value + ";" + project.Variables["ElmsStatus"].Value + ";" + project.Variables["ViewsElms"].Value + ";" + project.Variables["ElmsUrlTxt"].Value);
2624 break;
2625 }
2626 }
2627
2628 project.Variables["AdvLink"].Value = GoodsInCab.GetCell("H",h);
2629 project.SendInfoToLog(project.Variables["AdvLink"].Value,true);
2630 project.Variables["TimeOn"].Value = GoodsInCab.GetCell("I",h);
2631 project.SendInfoToLog(project.Variables["TimeOn"].Value,true);
2632 project.Variables["TimeOff"].Value = GoodsInCab.GetCell("J",h);
2633 project.SendInfoToLog("Время выключения - " + project.Variables["TimeOff"].Value,true);
2634 //instance.WaitForUserAction(50);
2635 project.Variables["WhatToDo"].Value = GoodsInCab.GetCell("K",h);
2636 project.SendInfoToLog(project.Variables["WhatToDo"].Value,true);
2637 string SetOn = GoodsInCab.GetCell("L",h);
2638 project.SendInfoToLog(SetOn,true);
2639 project.Variables["SetOff"].Value = GoodsInCab.GetCell("M",h);
2640 project.SendInfoToLog(project.Variables["SetOff"].Value,true);
2641 string PriceForFirstPlace = GoodsInCab.GetCell("N",h);
2642 project.SendInfoToLog(PriceForFirstPlace,true);
2643 string PriceForFirstPage = GoodsInCab.GetCell("O",h);
2644 project.SendInfoToLog(PriceForFirstPage,true);
2645 project.Variables["Archive"].Value = GoodsInCab.GetCell("P",h);
2646 project.SendInfoToLog(project.Variables["Archive"].Value,true);
2647 project.Variables["GoodsInSell"].Value = GoodsInCab.GetCell("Q",h);
2648 project.SendInfoToLog(project.Variables["GoodsInSell"].Value,true);
2649
2650 //}
2651
2652 if(String.IsNullOrWhiteSpace(project.Variables["TimeOn"].Value)){
2653 project.SendWarningToLog("Не заполнено время выключения для объявления - " + project.Variables["AdvLink"].Value + " пропускаем его",true);
2654 }else{
2655 project.SendInfoToLog("Работаем с объявлением - " + project.Variables["AdvLink"].Value,true);
2656 //instance.WaitForUserAction(50);
2657 instance.ActiveTab.NavigateWithCheck(project.Variables["AdvLink"].Value, DateTime.Now, 60, "");
2658 instance.ActiveTab.WaitDownloading();
2659 System.Threading.Thread.Sleep(rnd.Next(12500,15800));
2660
2661 //Определяем приклеенное объявление
2662 HtmlElement StickedYes = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card-head__link')]",0);
2663 string text = StickedYes.GetAttribute("innertext");
2664
2665 int NewSetOff = Convert.ToInt32(project.Variables["SetOff"].Value);
2666
2667 if(NewSetOff==0){
2668
2669 //instance.WaitForUserAction(300);
2670
2671 project.SendInfoToLog("Присвоена ставка " + project.Variables["SetOff"].Value + " - снимаем объявление: " + project.Variables["AdvLink"].Value,true);
2672 instance.ActiveTab.FullEmulationMouseMoveAboveHtmlElement(StickedYes, 10);
2673 System.Threading.Thread.Sleep(rnd.Next(8500,12800));
2674
2675 HtmlElement ChangePrice = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card__actions')]/a",0);
2676 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(ChangePrice);
2677 instance.ActiveTab.FullEmulationMouseClick("left","click");
2678 instance.ActiveTab.WaitDownloading();
2679 System.Threading.Thread.Sleep(rnd.Next(8500,12800));
2680
2681 HtmlElement ConfirmDeleteAdv = instance.ActiveTab.FindElementByXPath("//a[contains(@class, 'unstick')]",0);
2682 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(ConfirmDeleteAdv);
2683 instance.ActiveTab.FullEmulationMouseClick("left","click");
2684 instance.ActiveTab.WaitDownloading();
2685 System.Threading.Thread.Sleep(rnd.Next(8500,12800));
2686
2687 }else if(NewSetOff>0){
2688
2689 project.SendInfoToLog("Присвоена ставка " + project.Variables["SetOff"].Value + " - выключения, ставим ее для объявления: " + project.Variables["AdvLink"].Value,true);
2690
2691 //instance.WaitForUserAction(300);
2692
2693 System.Threading.Thread.Sleep(rnd.Next(12500,15800));
2694
2695 HtmlElement AlreadySticked = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'serviceStick')]/div",0);
2696
2697 string CtickedCheck = AlreadySticked.GetAttribute("innertext");
2698
2699 System.Threading.Thread.Sleep(rnd.Next(12500,15800));
2700
2701 if(CtickedCheck.Contains("Приклеено")){
2702
2703 //instance.WaitForUserAction(300);
2704
2705 instance.ActiveTab.FullEmulationMouseMoveAboveHtmlElement(AlreadySticked, rnd.Next(10,15));
2706 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
2707
2708 HtmlElement ChangePriceAdv = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'service-card__actions')]/a",0);
2709 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(ChangePriceAdv);
2710 instance.ActiveTab.FullEmulationMouseClick("left","click");
2711 instance.ActiveTab.WaitDownloading();
2712 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
2713
2714 HtmlElement AdvCancel = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'controlBody')]/input[contains(@name, 'stickPrice')]",0);
2715 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AdvCancel);
2716 instance.ActiveTab.FullEmulationMouseClick("left","click");
2717 instance.ActiveTab.WaitDownloading();
2718 System.Threading.Thread.Sleep(rnd.Next(2500,3800));
2719
2720 tab.KeyEvent("a","press","ctrl");
2721 System.Threading.Thread.Sleep(rnd.Next(1500,2800));
2722 tab.KeyEvent("Delete","press","");
2723 System.Threading.Thread.Sleep(rnd.Next(1500,2800));
2724
2725 instance.SendText(project.Variables["SetOff"].Value, rnd.Next(78,92));
2726
2727 instance.ActiveTab.WaitDownloading();
2728 System.Threading.Thread.Sleep(rnd.Next(500,1800));
2729
2730 HtmlElement ConfirmNewPrice = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'stick-form__content-block')]//button[contains(@type, 'submit')]",0);
2731 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(ConfirmNewPrice);
2732 instance.ActiveTab.FullEmulationMouseClick("left","click");
2733 instance.ActiveTab.WaitDownloading();
2734 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
2735
2736 }else{
2737
2738 //instance.WaitForUserAction(300);
2739
2740 System.Threading.Thread.Sleep(rnd.Next(12500,15800));
2741
2742 project.SendInfoToLog("Ставим ставку выключения для объявления: " + project.Variables["AdvLink"].Value,true);
2743 HtmlElement StickPress = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin-user-action-items')]//a[contains(@class, 'serviceStick')]",0);
2744 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(StickPress);
2745 instance.ActiveTab.FullEmulationMouseClick("left","click");
2746 instance.ActiveTab.WaitDownloading();
2747 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
2748
2749 HtmlElement StickedPress = instance.ActiveTab.FindElementByXPath("//input[contains(@name, 'stickPrice')]",0);
2750 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(StickedPress);
2751 instance.ActiveTab.FullEmulationMouseClick("left","click");
2752 instance.ActiveTab.WaitDownloading();
2753 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
2754
2755 tab.KeyEvent("a", "press", "ctrl");
2756 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
2757 tab.KeyEvent("Delete","press","");
2758 instance.SendText(project.Variables["SetOff"].Value,rnd.Next(67,89));
2759 tab.KeyEvent("Enter","press","");
2760 instance.ActiveTab.WaitDownloading();
2761 System.Threading.Thread.Sleep(rnd.Next(4500,7800));
2762 //button[contains(@type, 'submit')]
2763 HtmlElement StickConfirm = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'applier-s-submit__confirm')]//button[contains(@type, 'submit')]",0);
2764 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(StickConfirm);
2765 instance.ActiveTab.FullEmulationMouseClick("left","click");
2766 System.Threading.Thread.Sleep(rnd.Next(2500,4800));
2767 }
2768 }
2769 }
2770 }
2771 }
2772
2773 if(ChangeAdvOnly){
2774
2775 //Сначала сливаем в таблицу все что есть в личном кабинете, потом приступаем к изменениям объявлений.
2776 //Изменения идут по id в таблице GoodsInCab
2777 ParseYes();
2778
2779 IZennoTable Report = project.Tables["Report"];
2780 //IZennoTable ExportTable = project.Tables["ExportTable"];
2781
2782 //Перебираем строки в таблице с данными из ЛК
2783 for(int n=0;n <= GoodsInCab.RowCount;n++){
2784
2785 string IdForFarpost = GoodsInCab.GetCell("A",n);
2786 string GoodsName = GoodsInCab.GetCell("B",n);
2787
2788 if(WhereUpload=="Битрикс"){
2789
2790 List<string> AllNamesInExportTable = ExportTable.GetColumn("C").ToList();
2791
2792 string OneTxtName = AllNamesInExportTable[0];
2793 project.SendInfoToLog("Наименование товара в таблице экспорта - " + OneTxtName,true);
2794
2795 if(OneTxtName==GoodsName){
2796
2797 project.SendInfoToLog("Смотрим строку № - " + n,true);
2798
2799 //lock(SyncObjects.TableSyncer){
2800
2801 string Status = GoodsInCab.GetCell("F", n);
2802
2803 //Проверяем статус строки - актуально или в работе
2804 for(int rowNum=0;rowNum<=GoodsInCab.RowCount;rowNum++){
2805 if(Status=="Актуально"){
2806 GoodsInCab.SetCell("F", n, "В работе");
2807 rowNum=n;
2808 break;
2809 }
2810 }
2811
2812 //Взяли одну строку с Export таблицы
2813 string ID = ExportTable.GetCell("A",n);
2814 project.SendInfoToLog("ID - " + ID,true);
2815 string Category = ExportTable.GetCell("B",n);
2816 project.SendInfoToLog("Категория - " + Category,true);
2817 project.Variables["Name"].Value = ExportTable.GetCell("C",n);
2818 project.SendInfoToLog("Наименование товара - " + project.Variables["Name"].Value,true);
2819 project.Variables["Price"].Value = ExportTable.GetCell("D",n);
2820 project.SendInfoToLog("Цена товара - " + project.Variables["Price"].Value,true);
2821 string Description = ExportTable.GetCell("E",n);
2822 //project.SendInfoToLog("Описание товара - " + Description,true);
2823 string UpTime = ExportTable.GetCell("F", n);
2824 project.SendInfoToLog("Время поднятия объявления - " + UpTime,true);
2825 //Парсим описание, без спец символов
2826 project.Variables["NewDescription"].Value = new Regex(@"(?<=text-align:\ justify;"">)[\w\W]*?(?=<br>)").Match(Description).Value;
2827 project.SendInfoToLog("Описания товара - " + project.Variables["NewDescription"].Value,true);
2828
2829 //}
2830
2831 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/bulletin/" + IdForFarpost + "/edit", DateTime.Now, 60, "");
2832 instance.ActiveTab.WaitDownloading();
2833 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2834
2835 //Поле для ввода наименования товара
2836 HtmlElement AdvNameField = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]/input[contains(@class, 'bulletin_adding__subject_field__input')]",0);
2837 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AdvNameField);
2838 instance.ActiveTab.FullEmulationMouseClick("left","click");
2839 tab.KeyEvent("a","press","ctrl");
2840 instance.ActiveTab.WaitDownloading();
2841 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2842 tab.KeyEvent("Delete","press","");
2843 instance.ActiveTab.WaitDownloading();
2844 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2845 instance.SendText(project.Variables["Name"].Value, rnd.Next(65,92));
2846 instance.ActiveTab.WaitDownloading();
2847 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2848
2849 //Поле с ценой
2850 HtmlElement AdvPriceField = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]/input[contains(@name, 'price')]",0);
2851 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AdvPriceField);
2852 instance.ActiveTab.FullEmulationMouseClick("left","click");
2853 tab.KeyEvent("a","press","ctrl");
2854 instance.ActiveTab.WaitDownloading();
2855 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2856 tab.KeyEvent("Delete", "press", "");
2857 instance.ActiveTab.WaitDownloading();
2858 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2859 instance.SendText(project.Variables["Price"].Value, rnd.Next(55,82));
2860 instance.ActiveTab.WaitDownloading();
2861 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2862
2863 //Поле с описанием товара
2864 HtmlElement NewDescriptionField = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]//textarea[contains(@name, 'text')]",0);
2865 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(NewDescriptionField);
2866 instance.ActiveTab.FullEmulationMouseClick("left","click");
2867 tab.KeyEvent("a","press","ctrl");
2868 instance.ActiveTab.WaitDownloading();
2869 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2870 tab.KeyEvent("Delete", "press", "");
2871 instance.ActiveTab.WaitDownloading();
2872 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2873 instance.SendText(project.Variables["NewDescription"].Value, rnd.Next(55,82));
2874 instance.ActiveTab.WaitDownloading();
2875 System.Threading.Thread.Sleep(rnd.Next(9500, 14500));
2876
2877 //Проверяем сохранение изменений после редактирования
2878 HtmlElement AdvPriceFieldSave = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__submit')]/div[contains(@class, 'bulletin_adding__submit__save_note')]",0);
2879 string GreenMsg = AdvPriceFieldSave.GetAttribute("innertext");
2880
2881 if(GreenMsg=="Изменения сохранены"){
2882 project.SendInfoToLog("Изменения после редактирования успешно сохранены, идем к следующему объявлению",true);
2883 }
2884 }else{
2885 project.SendWarningToLog("Не найден совпадающий по названию товар, для изменения в таблице экспорта - file2 и таблице - экспорта всех товаров из личного кабинета за текущую дату в папке ../System/{-Имя аккаунта-}/{-Текущая дата-}.xlsx",true);
2886 }
2887
2888 }else{
2889
2890 string CabIdOnly = GoodsInCab.GetCell("A",n);
2891 string CabNameOnly = GoodsInCab.GetCell("B",n);
2892 string CabPriceOnly = GoodsInCab.GetCell("C",n);
2893 string CabTimePlace = GoodsInCab.GetCell("D",n);
2894 string CabAdvLink = GoodsInCab.GetCell("H",n);
2895
2896 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/bulletin/" + IdForFarpost + "/edit", DateTime.Now, 60, "");
2897 instance.ActiveTab.WaitDownloading();
2898 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2899
2900 //Поле для ввода наименования товара
2901 HtmlElement AdvNameField = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]/input[contains(@class, 'bulletin_adding__subject_field__input')]",0);
2902 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AdvNameField);
2903 instance.ActiveTab.FullEmulationMouseClick("left","click");
2904 tab.KeyEvent("a","press","ctrl");
2905 instance.ActiveTab.WaitDownloading();
2906 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2907 tab.KeyEvent("Delete","press","");
2908 instance.ActiveTab.WaitDownloading();
2909 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2910 instance.SendText(CabNameOnly, rnd.Next(65,92));
2911 instance.ActiveTab.WaitDownloading();
2912 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2913
2914 //Поле с ценой
2915 HtmlElement AdvPriceField = instance.ActiveTab.FindElementByXPath("/div[contains(@class, 'bulletin_adding__field__control')]/input[contains(@name, 'price')]",0);
2916 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AdvPriceField);
2917 instance.ActiveTab.FullEmulationMouseClick("left","click");
2918 tab.KeyEvent("a","press","ctrl");
2919 instance.ActiveTab.WaitDownloading();
2920 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2921 tab.KeyEvent("Delete", "press", "");
2922 instance.ActiveTab.WaitDownloading();
2923 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2924 instance.SendText(CabPriceOnly, rnd.Next(55,82));
2925 instance.ActiveTab.WaitDownloading();
2926 System.Threading.Thread.Sleep(rnd.Next(2500, 4500));
2927
2928 //Проверяем сохранение изменений после редактирования
2929 HtmlElement AdvPriceFieldSave = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__submit')]/div[contains(@class, 'bulletin_adding__submit__save_note')]",0);
2930 string GreenMsg = AdvPriceFieldSave.GetAttribute("innertext");
2931
2932 if(GreenMsg=="Изменения сохранены"){
2933 project.SendInfoToLog("Изменения после редактирования успешно сохранены, идем к следующему объявлению",true);
2934 }
2935 }
2936 }
2937 }
2938
2939 //Сравнение двух таблиц - экспорта и выгрузки из ЛК за текущий день
2940 //GoodsInCab - здесь удаляем строки, которых нет в таблице - выгрузке
2941 //ExportTable - таблица - выгрузки
2942
2943 //Загружаем товары из таблицы в личный кабинет после захода в него
2944 if(new_goods_upload){
2945
2946 if(CommonData.Debug) project.SendWarningToLog("ExportTable - старт проверки таблиц",true);
2947
2948
2949 for(int n=0;n<=ExportTable.RowCount;n++){
2950
2951 string NameLK = GoodsInCab.GetCell("B",n);
2952 project.SendInfoToLog("Наименование - " + NameLK,true);
2953 string PriceLK = GoodsInCab.GetCell("C",n);
2954 project.SendInfoToLog("Цена - " + PriceLK,true);
2955
2956 if(CommonData.Debug) project.SendWarningToLog("ExportTable - 1",true);
2957
2958 if(WhereUpload=="Битрикс"){
2959
2960 project.SendInfoToLog("Включена работа с таблицей 'Битрикс' ",true);
2961 project.Variables["Name"].Value = ExportTable.GetCell("C",x);
2962 project.SendInfoToLog("Наименование - " + project.Variables["Name"].Value,true);
2963 project.Variables["Price"].Value = ExportTable.GetCell("D",x);
2964 project.SendInfoToLog("Цена - " + project.Variables["Price"].Value,true);
2965
2966 if(CommonData.Debug) project.SendWarningToLog("ExportTable - 1_1",true);
2967
2968 //Оставляем в таблице ЛК только те товары, которые надо удалить с фарпост
2969 if(project.Variables["Name"].Value==NameLK & project.Variables["Price"].Value==PriceLK){
2970 GoodsInCab.DeleteRow(n);
2971 if(CommonData.Debug) project.SendWarningToLog("ExportTable - 2",true);
2972 project.SendInfoToLog("Удалили совпадающую строку из таблицы - " + GoodsInCab,true);
2973 }
2974
2975 DelAdvs();
2976
2977 if(CommonData.Debug) project.SendWarningToLog("ExportTable - конец проверки таблиц",true);
2978
2979 AdvsUpToTime();
2980
2981 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/adding", DateTime.Now, 60, "");
2982 instance.ActiveTab.WaitDownloading();
2983 System.Threading.Thread.Sleep(rnd.Next(6500, 12500));
2984
2985 //Ищем кнопку 'Продам товары'
2986 HtmlElement GoodsSell = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'typeControlFarPost')]/a[1]",0);
2987 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(GoodsSell);
2988 project.SendInfoToLog("Жмем 'Продать товары' ",true);
2989 instance.ActiveTab.FullEmulationMouseClick("left","click");
2990 instance.ActiveTab.WaitDownloading();
2991 System.Threading.Thread.Sleep(rnd.Next(6500, 10500));
2992
2993 //Если появилось поле для ввода города, когда сменилось местоположение работы шаблона
2994 //Берем город с настроек
2995 HtmlElement SityEnter = instance.ActiveTab.FindElementByXPath("//input[contains(@class, 'search')]",0);
2996
2997 if(!SityEnter.IsVoid){
2998 tab.FullEmulationMouseMoveToHtmlElement(SityEnter);
2999 project.SendInfoToLog("Вводим город",true);
3000 instance.ActiveTab.FullEmulationMouseClick("left","click");
3001 instance.SendText(project.Variables["sity_name"].Value, rnd.Next(67,89));
3002 instance.ActiveTab.WaitDownloading();
3003 System.Threading.Thread.Sleep(rnd.Next(6500, 10500));
3004
3005 HtmlElement RightSity = instance.ActiveTab.FindElementByXPath(String.Format("//li[contains(@class, 'best-selected')]/a/span[contains(text(), '{0}')]", project.Variables["sity_name"].Value), 0);
3006 project.SendInfoToLog("Выбираем город - " + project.Variables["sity_name"].Value,true);
3007 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(RightSity);
3008 instance.ActiveTab.FullEmulationMouseClick("left","click");
3009 instance.ActiveTab.WaitDownloading();
3010 System.Threading.Thread.Sleep(rnd.Next(6500, 10500));
3011 }
3012
3013 //Заполняем заголовок названием товара из таблицы экспорта
3014 HtmlElement AdvName = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]/input",0);
3015 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AdvName);
3016 project.SendInfoToLog("Заполняем заголовок названия товара",true);
3017 instance.ActiveTab.FullEmulationMouseClick("left","click");
3018 instance.ActiveTab.WaitDownloading();
3019 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3020 project.SendInfoToLog("Очищаем поле для ввода текста",true);
3021 TextDel();
3022 instance.SendText(project.Variables["Name"].Value, rnd.Next(43,78));
3023 System.Threading.Thread.Sleep(rnd.Next(2500, 8500));
3024
3025 instance.ActiveTab.KeyEvent("Tab", "press", "");
3026 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3027
3028 //Пробуем выбрать рекомендованную категорию по кнопку 'Выбрать другой'
3029 HtmlElement AdvNameBtn = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'cell-control')]/button",0);
3030
3031 if(!AdvNameBtn.IsVoid){
3032
3033 project.SendInfoToLog("Категория еще не выбрана, выбираем нужную",true);
3034 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(AdvNameBtn);
3035 instance.ActiveTab.FullEmulationMouseClick("left","click");
3036 instance.ActiveTab.WaitDownloading();
3037 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3038
3039 //Кликаем на рекомендуемую категорию в первом столбце
3040 HtmlElement FirstRec = instance.ActiveTab.FindElementByXPath("//ul/li[contains(@class, 'tree_select__level')][1]/ul/li/a[contains(@class, 'active-item js__selected')]|//ul/li[contains(@class, 'tree_select__level')][1]/ul/li/a[contains(@class, 'active-item js__recommended js__selected')]",0);
3041 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(FirstRec);
3042 instance.ActiveTab.FullEmulationMouseClick("left","click");
3043 instance.ActiveTab.WaitDownloading();
3044 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3045
3046 //Кликаем на конечную рекомендованную категорию в 3м столбце
3047 HtmlElement TherdRec = instance.ActiveTab.FindElementByXPath("//ul/li[contains(@class, 'tree_select__level')][3]/ul/li/a[contains(@class, 'tree_select__node js__selected')]|//ul/li[contains(@class, 'tree_select__level')][3]/ul/li/a[contains(@class, 'tree_select__node js__recommended js__selected",0);
3048 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(TherdRec);
3049 project.SendInfoToLog("Выбираем рекомендованную категорию",true);
3050 instance.ActiveTab.FullEmulationMouseClick("left","click");
3051 instance.ActiveTab.WaitDownloading();
3052 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3053
3054 }
3055
3056 //Клик на один товар
3057 HtmlElement LoneGoodBtn = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin-type__variant-caption')]/span[contains(text(), 'Один товар')]",0);
3058 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(LoneGoodBtn);
3059 project.SendInfoToLog("Кликаем на кнопку 'Один товар' ",true);
3060 instance.ActiveTab.FullEmulationMouseClick("left","click");
3061 instance.ActiveTab.WaitDownloading();
3062 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3063
3064 //Клик на новый
3065 HtmlElement NewBtn = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'radio_option')]//input//following-sibling::label[contains(text(), 'Новый')]",0);
3066 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(NewBtn);
3067 project.SendInfoToLog("Кликаем на кнопку 'Новый товар' ",true);
3068 instance.ActiveTab.FullEmulationMouseClick("left","click");
3069 instance.ActiveTab.WaitDownloading();
3070 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3071
3072 //Клик на поле с ценой
3073 HtmlElement NewBtn2 = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]/input[contains(@type, 'number')]",0);
3074 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(NewBtn2);
3075 project.SendInfoToLog("Пишем цену",true);
3076 instance.ActiveTab.FullEmulationMouseClick("left","click");
3077 instance.ActiveTab.WaitDownloading();
3078 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3079 project.SendInfoToLog("Очищаем поле для ввода текста",true);
3080 TextDel();
3081 instance.SendText(project.Variables["Price"].Value, rnd.Next(45,87));
3082 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3083
3084 //Ввод текста объявления в нужное поле
3085 HtmlElement TxtField = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]/textarea[contains(@class, 'bulletin_adding__field__input')]",0);
3086 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(TxtField);
3087 project.SendInfoToLog("Вставляем нужный текст - описание товара по ctrl+v ",true);
3088 instance.ActiveTab.FullEmulationMouseClick("left","click");
3089 project.SendInfoToLog("Очищаем поле для ввода текста",true);
3090 TextDel();
3091 instance.ActiveTab.WaitDownloading();
3092
3093 lock(SyncObjects.InputSyncer){
3094
3095 string prev_txt = null;
3096 prev_txt = System.Windows.Forms.Clipboard.GetText();
3097
3098 var desrc = project.Variables["NewDescription"].Value;
3099 System.Windows.Forms.Clipboard.SetText(desrc);
3100 instance.ActiveTab.KeyEvent("v", "press", "ctrl");
3101 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3102 System.Windows.Forms.Clipboard.Clear();
3103 System.Windows.Forms.Clipboard.SetText(prev_txt);
3104
3105 }
3106
3107 PageScrollingToBottom();
3108 //Нажимаем кнопку оплатить
3109 switch(project.Variables["SendAdvChoose"].Value){
3110 case "Опубликовать платно":
3111 HtmlElement PayedSend = instance.ActiveTab.FindElementByXPath("//button[@id='bulletin_publication_paid']",0);
3112 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(PayedSend);
3113 project.SendInfoToLog("Выбрана платная публикация",true);
3114 instance.ActiveTab.FullEmulationMouseClick("left","click");
3115 instance.ActiveTab.WaitDownloading();
3116 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3117 break;
3118 case "Опубликовать бесплатно":
3119 HtmlElement FreeSend = instance.ActiveTab.FindElementByXPath("//button[@id='bulletin_publication_free']",0);
3120 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(FreeSend);
3121 project.SendInfoToLog("Выбрана платная публикация",true);
3122 instance.ActiveTab.FullEmulationMouseClick("left","click");
3123 instance.ActiveTab.WaitDownloading();
3124 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3125 break;
3126 default:
3127 project.SendInfoToLog("По умолчанию выбрана опция оплатить и опубликовать",true);
3128 HtmlElement SpecialSend = instance.ActiveTab.FindElementByXPath("//button[@id='bulletin_publication_hiddenContact']",0);
3129 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(SpecialSend);
3130 instance.ActiveTab.FullEmulationMouseClick("left","click");
3131 instance.ActiveTab.WaitDownloading();
3132 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3133 break;
3134 }
3135
3136 //Если закончились средства на счете фарпост
3137 HtmlElement Balance = instance.ActiveTab.FindElementByXPath("//div[contains(@class, 'bill-amount-value-item user-balance')]",0);
3138 string BalCount = Balance.GetAttribute("innertext");
3139 if(BalCount.Contains("0 р.")){
3140 project.SendWarningToLog("Закончился баланс в личном кабинете, сейчас средств на счете - " + BalCount,true);
3141 break;
3142 }
3143
3144 //Выбираем 'Оплатить объявление'
3145 HtmlElement PayForAdv = instance.ActiveTab.FindElementByXPath("//button[@type='submit']",0);
3146 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(PayForAdv);
3147 instance.ActiveTab.FullEmulationMouseClick("left","click");
3148 instance.ActiveTab.WaitDownloading();
3149 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3150
3151 }else{
3152 project.SendInfoToLog("Включена работа с таблицей 'Мой склад' - изменяем товары, согласно таблице - выгрузке",true);
3153 string IDCab = ExportTable.GetCell("A",n);
3154 project.SendInfoToLog("ID - " + IDCab,true);
3155 string PriceCab = ExportTable.GetCell("C",n);
3156 project.SendInfoToLog("Цена - " + PriceCab,true);
3157
3158 //Сюда вставляем работу с изменениями объявлений при работе с таблицей с Моего склад
3159 DelAdvs();
3160
3161 if(CommonData.Debug) project.SendWarningToLog("ExportTable - конец проверки таблиц",true);
3162
3163 AdvsUpToTime();
3164
3165 instance.ActiveTab.NavigateWithCheck("https://www.farpost.ru/bulletin/" + IDCab + "/edit", DateTime.Now, 60, "");
3166 instance.ActiveTab.WaitDownloading();
3167 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3168
3169 HtmlElement PriceBtn = tab.FindElementByXPath("//div[contains(@class, 'bulletin_adding__field__control')]/input[contains(@type, 'number')]",0);
3170 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(PriceBtn);
3171 instance.ActiveTab.FullEmulationMouseClick("left","click");
3172 instance.ActiveTab.WaitDownloading();
3173 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3174
3175 tab.KeyEvent("A", "press", "ctrl");
3176 System.Threading.Thread.Sleep(rnd.Next(4500, 8500));
3177 instance.SendText(PriceCab, 78);
3178 tab.KeyEvent("Tab", "press", "");
3179 }
3180
3181 }
3182
3183 }
3184
3185 //Парсим данные на основании таблицы - выгрузки, если включена опция
3186 if(ParseWithTable){
3187 project.SendInfoToLog("Парсим категории, на основании категорий в таблице - выгрузки",true);
3188 ParseBlockExport();
3189 }
3190 }
3191 }
3192
3193 if(ParseWithTable){
3194 //вбиваем в поиск нужную категорию для скана, либо берем ее из таблицы
3195 if(CommonData.Debug) project.SendWarningToLog("NeededCat: 6",true);
3196 HtmlElement NeededCat = tab.FindElementByXPath("//input[contains(@id, 'search')]",0);
3197 if(table_only){
3198 if(CommonData.Debug) project.SendWarningToLog("NeededCat: 7",true);
3199 tab.Touch.SwipeIntoView(NeededCat);
3200 tab.Touch.Touch(NeededCat);
3201 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
3202 instance.SendText(cat_name, rnd.Next(67,89));
3203 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
3204 tab.KeyEvent("ENTER", "press", "");
3205 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
3206 }else{
3207 if(CommonData.Debug) project.SendWarningToLog("NeededCat: 8",true);
3208 tab.FullEmulationMouseMoveToHtmlElement(NeededCat);
3209 tab.FullEmulationMouseClick("left","click");
3210 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
3211 instance.SendText(cat_name, rnd.Next(67,89));
3212 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
3213 tab.KeyEvent("ENTER", "press", "");
3214 System.Threading.Thread.Sleep(rnd.Next(500, 2000));
3215 }
3216
3217 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
3218
3219 FileCheck();
3220
3221 //Общий блок с товарами
3222 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
3223 //Блок парсинга
3224 if(CommonData.Debug) project.SendWarningToLog("parents: 2",true);
3225
3226 System.Threading.Thread.Sleep(rnd.Next(4500, 6000));
3227
3228 //Прокрутка страницы до подвала
3229 PageScrollingToBottom();
3230
3231 //Блок парсинга
3232 ParseBlock();
3233
3234 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
3235 instance.ActiveTab.WaitDownloading();
3236 //Конец блока парсинга
3237 if(CommonData.Debug) project.SendWarningToLog("TableToWrite: 22",true);
3238
3239 if(same_goods){
3240
3241 //Проверяем - нужно ли парсить блоки с похожими товарами
3242 IZennoTable TableToWrite = project.Tables["Report"];
3243
3244 //Перебираем все ссылки на страницы, парсим похожие товары
3245 for(int x=0;x<=TableToWrite.RowCount;x++){
3246 string LoneUrl = TableToWrite.GetCell("H",x);
3247 string LoneIndex = TableToWrite.GetCell("A",x);
3248
3249 project.SendInfoToLog("Открываем url - " + LoneUrl,true);
3250 instance.ActiveTab.Navigate(LoneUrl);
3251 instance.ActiveTab.WaitDownloading();
3252 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
3253
3254 //Ищем кнопку 'показать еще объявления'
3255 project.SendInfoToLog("Ищем кнопку 'Показать все объявления' ",true);
3256 HtmlElement NextButton = instance.ActiveTab.FindElementByXPath("//a[contains(@class, 'similar-bulletins-block__show-more')]",0);
3257
3258 if(NextButton.IsVoid){
3259 if(Mobile){
3260 instance.ActiveTab.Touch.SwipeIntoView(NextButton);
3261 instance.ActiveTab.Touch.Touch(NextButton);
3262 instance.ActiveTab.WaitDownloading();
3263 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
3264 }else{
3265 instance.ActiveTab.FullEmulationMouseWheel(NextButton);
3266 instance.ActiveTab.FullEmulationMouseMoveToHtmlElement(NextButton);
3267 instance.ActiveTab.FullEmulationMouseClick("left","click");
3268 instance.ActiveTab.WaitDownloading();
3269 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
3270 }
3271 }else{
3272 break;
3273 }
3274
3275 }
3276
3277 //Парсим все похожие товары на странице
3278 ParseBlock();
3279 System.Threading.Thread.Sleep(rnd.Next(2500, 4000));
3280 }
3281
3282 }
3283
3284}
3285
3286
3287 public void BannerClose(){
3288
3289 try{
3290 if(CommonData.Debug) project.SendWarningToLog("BannerClose - старт метода",true);
3291
3292 Tab tab = instance.ActiveTab;
3293 Random rnd = new Random();
3294
3295 int RndClk = rnd.Next(0,100);
3296 if(CommonData.Debug) project.SendWarningToLog("BannerClose - 1",true);
3297 if(RndClk >= 10 && RndClk <= 100 || Mobile){
3298 project.SendInfoToLog("Вероятность закрытия PopUp - 90%, закрываем окошко",true);
3299 HtmlElement BannerClose = tab.FindElementByXPath("//button[contains(@class,'distr-smartbanner__control_type_close')]|//span[contains(text(), 'Закрыть')]",0);
3300 if(CommonData.Debug) project.SendWarningToLog("BannerClose - 2",true);
3301 int BnrHeight = Convert.ToInt32(BannerClose.GetAttribute("height"));
3302
3303 if(BnrHeight < 10){
3304 if(CommonData.Debug) project.SendWarningToLog("BannerClose - 3",true);
3305 project.SendWarningToLog("Высота элемента баннера < 10px, пропускаем работу с ним...",true);
3306 }else if(BnrHeight == 0){
3307 if(CommonData.Debug) project.SendWarningToLog("BannerClose - 4",true);
3308 project.SendWarningToLog("Высота элемента баннера = 0px, пропускаем работу с ним...",true);
3309 }else{
3310 if(!BannerClose.IsVoid){
3311 if(Mobile){
3312 if(CommonData.Debug) project.SendWarningToLog("BannerClose - 5",true);
3313 tab.Touch.Touch(BannerClose);
3314 System.Threading.Thread.Sleep(rnd.Next(700,1500));
3315 CloseAllTabs();
3316 }else{
3317 if(CommonData.Debug) project.SendWarningToLog("BannerClose - 6",true);
3318 tab.FullEmulationMouseMoveToHtmlElement(BannerClose);
3319 tab.FullEmulationMouseClick("left","click");
3320 System.Threading.Thread.Sleep(rnd.Next(700,1500));
3321 CloseAllTabs();
3322 }
3323 }
3324 }
3325 }
3326 if(CommonData.Debug) project.SendWarningToLog("BannerClose - завершение метода",true);
3327 }catch{}
3328 }
3329
3330 public void YaBrausPopupClose(){
3331 try{
3332 Tab tab = instance.ActiveTab;
3333 Random rnd = CommonData.Random;
3334
3335 HtmlElement YaBrausClose = tab.FindElementByXPath("//button[contains(@class, 'control_type_close')]",0);
3336 if(Mobile){
3337 tab.Touch.SwipeIntoView(YaBrausClose);
3338 tab.Touch.Touch(YaBrausClose);
3339 }else{
3340 tab.FullEmulationMouseMoveToHtmlElement(YaBrausClose);
3341 tab.FullEmulationMouseClick("left","click");
3342 }
3343 }catch{}
3344 }
3345
3346 public void MouseWheel2(){
3347
3348 Tab tab = instance.ActiveTab;
3349 Random rnd = new Random();
3350
3351 try{ClosePopup();}catch{}
3352
3353 int WheelTimes = rnd.Next(5, 10);
3354
3355 int direction = rnd.Next(0, 100)<70?-1:1;
3356
3357 for(int i=1;i<=WheelTimes;i++){
3358 tab.FullEmulationMouseWheel(0, rnd.Next(300, 800)*direction);
3359 System.Threading.Thread.Sleep(rnd.Next(300, 1200));
3360 }
3361 }
3362
3363 public void ClosePopup(){
3364
3365 if (CommonData.Debug) project.SendWarningToLog("ClosePopup: запуск метода (debug)", true);
3366 Tab tab = instance.ActiveTab;
3367 Random rnd = CommonData.Random;
3368 if (CommonData.Debug) project.SendWarningToLog("ClosePopup: 1 (debug)", true);
3369 IZennoList popups = project.Lists["popup_pathes"];
3370
3371 if (popups.Count==0) return;
3372
3373 for (int i=0; i<popups.Count; i++){
3374 try{
3375 if (String.IsNullOrWhiteSpace(popups[i])) continue;
3376 HtmlElement PopUpClose = tab.FindElementByXPath(popups[i],0);
3377 int PopUpHeight = Convert.ToInt32(PopUpClose.GetAttribute("height"));
3378 project.SendInfoToLog("Размер элемента PopUp - " + PopUpHeight,true);
3379
3380 if(PopUpHeight < 10){
3381 project.SendWarningToLog("Размер элемента popup < 10px - пропускаем клик...",true);
3382 break;
3383 }else if(PopUpHeight == 0){
3384 project.SendWarningToLog("Размер элемента popup = 0px - пропускаем клик...",true);
3385 break;
3386 }else{
3387 if (CommonData.Debug) project.SendWarningToLog("ClosePopup: 2 (debug)", true);
3388 if (!PopUpClose.IsVoid) {
3389 tab.FullEmulationMouseMoveToHtmlElement(PopUpClose);
3390 tab.FullEmulationMouseClick("left","click");
3391 tab.WaitDownloading();
3392 System.Threading.Thread.Sleep(rnd.Next(800,1500));
3393 if (CommonData.Debug) project.SendWarningToLog("ClosePopup: 3 (debug)", true);
3394 }
3395 }
3396
3397 }catch{}
3398 }
3399 if (CommonData.Debug) project.SendWarningToLog("ClosePopup: завершение метода (debug)", true);
3400
3401 }
3402 }
3403
3404 public class WebHelper{
3405
3406 public WebHelper(Instance NewInstance, IZennoPosterProjectModel NewProject, bool mobile){
3407 instance = NewInstance;
3408 project = NewProject;
3409
3410 Mobile = mobile;
3411 }
3412
3413 public Instance instance;
3414 public IZennoPosterProjectModel project;
3415
3416 public bool Mobile;
3417
3418 public HtmlElement LastElement;
3419
3420 public string LastXPath;
3421
3422 //public bool Ignore=false;
3423
3424 public void MouseMoveTo(HtmlElement elTarget, bool NoScroll=false){
3425 Tab tab = instance.ActiveTab;
3426
3427
3428 if (!NoScroll) tab.FullEmulationMouseWheel(elTarget);
3429 tab.FullEmulationMouseMoveToHtmlElement(elTarget);
3430
3431 }
3432
3433 public void MouseMoveTo(string XPath, bool safeClick=false, int Timeout=15){
3434 Tab Tab1 = instance.ActiveTab;
3435 HtmlElement elTarget = GetElement(XPath, Timeout);
3436
3437 MouseMoveTo(elTarget, safeClick);
3438
3439 }
3440
3441 public void ScrollTo(HtmlElement element, int minTopPosition = 100, int maxTopPosition = 600, bool safeScroll=false){
3442
3443 //project.SendInfoToLog("scrollTo");
3444
3445 if (element.IsVoid) throw new Exception("ScrollTo: элемент отсутствует на странице");
3446
3447 if (element.DisplacementInBrowser.X<0 || element.DisplacementInBrowser.Y<0)
3448 throw new Exception(String.Format("ScrollTo: элемент находится за пределами отображаемой области браузера (x{0}y{1})", element.DisplacementInBrowser.X, element.DisplacementInBrowser.Y));
3449
3450 if (element.DisplacementInBrowser.Y<minTopPosition) minTopPosition=element.DisplacementInBrowser.Y-50;
3451
3452 Tab Tab1 = instance.ActiveTab;
3453 while(true){
3454
3455
3456 if (element.DisplacementInTabWindow.Y>=minTopPosition && element.DisplacementInTabWindow.Y<=maxTopPosition) break;
3457
3458 int direction = 1;
3459 if (element.DisplacementInTabWindow.Y < minTopPosition) direction = -1;
3460
3461 int positionBefore = element.DisplacementInTabWindow.Y;
3462
3463 int rolls = CommonData.Random.Next(3, 11);
3464 for (int i=0; i<rolls; i++){
3465 //if (element.DisplacementInTabWindow.Y>=minTopPosition && element.DisplacementInTabWindow.Y<=maxTopPosition) break;
3466
3467 Tab1.MouseWheel(Tab1.FullEmulationMouseCurrentPosition.X, Tab1.FullEmulationMouseCurrentPosition.Y, 0, 50*direction, false);
3468 System.Threading.Thread.Sleep(CommonData.Random.Next(15, 25));
3469
3470 //Tab1.FullEmulationMouseCurrentPosition = new Point(Tab1.FullEmulationMouseCurrentPosition.X, Tab1.FullEmulationMouseCurrentPosition.Y+(element.DisplacementInTabWindow.Y-positionBefore));
3471 }
3472
3473 if (positionBefore == element.DisplacementInTabWindow.Y) {
3474 if (safeScroll){
3475 throw new Exception("Позиция целевого элемента больше не меняется в результате прокручивания");
3476 }else{
3477 return;
3478 }
3479 }
3480
3481 System.Threading.Thread.Sleep(CommonData.Random.Next(150, 350));
3482
3483 }
3484
3485 }
3486
3487 public void Click(HtmlElement elTarget, bool FullEmulation=true, bool NoScroll=false){
3488
3489 Tab Tab1 = instance.ActiveTab;
3490
3491 if (elTarget.IsVoid) throw new Exception("Click: Элемент не существует на странице");
3492
3493 if (FullEmulation){
3494
3495 System.Threading.Thread.Sleep(CommonData.Random.Next(50, 150));
3496
3497 MouseMoveTo(elTarget, NoScroll);
3498 Tab1.FullEmulationMouseClick("left", "click");
3499
3500
3501 }else{
3502 elTarget.Click();
3503 }
3504
3505 LastElement = elTarget;
3506
3507 }
3508
3509 public void Click(string XPath, bool FullEmulation=true, int Timeout=45, bool NoScroll=false){
3510
3511 HtmlElement elTarget = GetElement(XPath, Timeout);
3512 Click(elTarget, FullEmulation, NoScroll);
3513
3514 }
3515
3516 public void SetValue(string XPath, string Value, bool safeClick=true, bool FullEmulation=true, int Timeout=45){
3517
3518 Tab Tab1 = instance.ActiveTab;
3519
3520 HtmlElement elTarget = GetElement(XPath, Timeout);
3521
3522 if (FullEmulation){
3523 Click(XPath, FullEmulation, Timeout);
3524 instance.SendText(Value, CommonData.Random.Next(4, 12));
3525 }else{
3526 elTarget.SetValue(Value, "Middle", false, false);
3527 }
3528
3529 LastElement = elTarget;
3530
3531 }
3532
3533 public HtmlElement GetElement(string XPath, int Timeout=45){
3534
3535 LastXPath = XPath;
3536
3537 DateTime dtTimeOut = DateTime.Now.AddSeconds(Timeout);
3538
3539 HtmlElement elTarget = null;
3540 Tab Tab1 = instance.ActiveTab;
3541
3542 while(true){
3543 elTarget = Tab1.FindElementByXPath(XPath, 0);
3544 if (!elTarget.IsVoid && elTarget.BoundingClientWidth>0 && elTarget.BoundingClientHeight>0) break;
3545
3546 System.Threading.Thread.Sleep(250);
3547 if (DateTime.Now>dtTimeOut) throw new Exception(String.Format("Не удалось получить элемент '{0}' за '{1}' секунд", XPath, Timeout));
3548 }
3549
3550 return elTarget;
3551
3552 }
3553
3554 }
3555
3556}
3557
3558namespace ZennoLab.OwnCode
3559{
3560 public static class CommonData{
3561
3562 public static int CurrentHour;
3563
3564 public static int FirstMinute;
3565
3566 public static object Locker = new Object();
3567
3568 public static Dictionary<int, int> Schedule = new Dictionary<int, int>();
3569
3570 public static void Cleanup(){
3571 CurrentHour = 0;
3572 FirstMinute = 0;
3573 Schedule = new Dictionary<int, int>();
3574 }
3575
3576 public static List<string> YandexKeys = new List<string>();
3577
3578
3579 }
3580
3581 /// <summary>
3582 /// A simple class of the common code
3583 /// </summary>
3584 public class CommonCode
3585 {
3586 /// <summary>
3587 /// Lock this object to mark part of code for single thread execution
3588 /// </summary>
3589 public static object SyncObject = new object();
3590
3591 //WalkCode
3592 //FullWalkCode
3593
3594 //Прокрутка мышкой для после захода на сайты "до" и "после"
3595 public static void MouseWheel (IZennoPosterProjectModel project, Instance instance){
3596 Tab tab = instance.ActiveTab;
3597 Random rnd = new Random();
3598 int x = rnd.Next(300, 1600);
3599 int x1 = rnd.Next(400, 2100);
3600 int y = rnd.Next(-600, -100);
3601 int y1 = rnd.Next(-700, -200);
3602 tab.FullEmulationMouseWheel(x,x1);
3603 tab.FullEmulationMouseWheel(y,y1);
3604 System.Threading.Thread.Sleep(rnd.Next(x,x1));
3605
3606 }
3607 }
3608}
3609
3610namespace ZennoXml
3611{
3612
3613 public static class Reader{
3614
3615
3616 public static Task ZennoTask = new Task();
3617
3618 public static void RefreshData(IZennoPosterProjectModel project){
3619
3620 try{
3621 ZennoTask = ZennoXml.Reader.GetData(project);
3622 project.SendInfoToLog(String.Format("Получены данные: количество попыток {0}, максимальное количество потоков {1}. Проект остановлен: {2}",
3623 ZennoTask.ExecutionSettings.NumberOfTries, ZennoTask.ExecutionSettings.LimitOfThreads,
3624 ZennoTask.ExecutionSettings.Status=="Stop".ToString()), true);
3625 }catch(Exception e){
3626 project.SendWarningToLog("Ошибка получения данных о проекте ZennoPoster (проект выполняется в ProjectMaker? сменился id проекта?)", true);
3627 throw e;
3628 }
3629
3630 }
3631
3632 public static Task GetData(IZennoPosterProjectModel Project){
3633
3634 XmlSerializer Serializer = new XmlSerializer(typeof(Task));
3635
3636 Task Task = null;
3637 using (TextReader TextReader = new StringReader("<Task>" + ZennoPoster.GetTaskInfo(new Guid(Project.TaskId))+"</Task>")){
3638 Task = (Task)Serializer.Deserialize(TextReader);
3639 }
3640
3641 return Task;
3642
3643 }
3644
3645// public static bool ProjectIsStopped(IZennoPosterProjectModel Project){
3646// ZennoXml.Task ZennoTask = null;
3647// try{
3648// ZennoTask = GetData(Project);
3649// }catch{
3650// return false;
3651// }
3652//
3653// return ZennoTask.ExecutionSettings.Status=="Stop";
3654// }
3655
3656 }
3657
3658 public class ExecutionSettings {
3659 public string Id { get; set; }
3660 public int LimitOfThreads { get; set; }
3661 public int MaxAllowOfThreads { get; set; }
3662 public int DoneSuccesfully { get; set; }
3663 public int DoneAll { get; set; }
3664 public int NumberOfTries { get; set; }
3665 public int LastNumberOfTries { get; set; }
3666 public int Priority { get; set; }
3667 public string Proxy { get; set; }
3668 public string Status { get; set; }
3669 public string ProxyLabels { get; set; }
3670 public string ShouldBeExecutedRandomly { get; set; }
3671 public string GroupLabels { get; set; }
3672 public string GroupStates { get; set; }
3673 public string MaxNumOfSuccesStop { get; set; }
3674 public string MaxNumOfFailStop { get; set; }
3675 public string NumOfFailStop { get; set; }
3676 public string ShowTask { get; set; }
3677 public string TraceTask { get; set; }
3678 }
3679
3680 public class SchedulerSettings {
3681 public string Id { get; set; }
3682 public string StartDate { get; set; }
3683 public string ShedulerOnDate { get; set; }
3684 public string EndDate { get; set; }
3685 public string RepetitionCount { get; set; }
3686 public string ScheduleType { get; set; }
3687 public string RepeatType { get; set; }
3688 public string ActivateTime { get; set; }
3689 public string ActivateWorkTime { get; set; }
3690 public string IsActive { get; set; }
3691 public string NumberOfTries { get; set; }
3692 public string Minutes { get; set; }
3693 public string Days { get; set; }
3694 public string LastScheduleDate { get; set; }
3695 public string NextScheduleDate { get; set; }
3696 public string IsClearSucces { get; set; }
3697 public string GroupName { get; set; }
3698 }
3699
3700 public class TriggerSettings {
3701 public string Id { get; set; }
3702 public string CheckFileExistanse { get; set; }
3703 public string CheckFilePath { get; set; }
3704 public string RemoveCheckFile { get; set; }
3705 public string NumberOfTries { get; set; }
3706 public string IsClearSucces { get; set; }
3707 }
3708
3709 public class Project {
3710 public string ProjectFileLocation { get; set; }
3711 public string ProjectType { get; set; }
3712 }
3713
3714 public class Task {
3715 public string Id { get; set; }
3716 public string Name { get; set; }
3717 public string IsNewbie { get; set; }
3718 public string IsEnable { get; set; }
3719 public string CreateTime { get; set; }
3720 public string SettingsType { get; set; }
3721 public ExecutionSettings ExecutionSettings { get; set; }
3722 public SchedulerSettings SchedulerSettings { get; set; }
3723 public TriggerSettings TriggerSettings { get; set; }
3724 public Project Project { get; set; }
3725 }
3726
3727}
3728
3729
3730
3731namespace MouseEmulation
3732{
3733 public class MouseEmulator
3734 {
3735 private const uint MAPVK_VK_TO_CHAR = 2;
3736
3737 private const int MOUSEEVENTF_LEFTDOWN = 2;
3738
3739 private const int MOUSEEVENTF_LEFTUP = 4;
3740
3741 private const int MOUSEEVENTF_MOVE = 1;
3742
3743 private const int WM_MOUSEMOVE = 512;
3744
3745 private const int MOUSEEVENTF_WHEEL = 2048;
3746
3747 private const int MOUSEEVENTF_ABSOLUTE = 32768;
3748
3749 private const int WM_MOUSEWHEEL = 522;
3750
3751 private const int WM_SCROLL = 276;
3752
3753 private const int WM_VSCROLL = 277;
3754
3755 [ThreadStatic]
3756 public static IZennoPosterProjectModel project;
3757
3758 [ThreadStatic]
3759 public static Instance instance;
3760
3761 [ThreadStatic]
3762 public static int CurrentX;
3763
3764 [ThreadStatic]
3765 public static int CurrentY;
3766
3767 [ThreadStatic]
3768 public static int WorkTabHandle;
3769
3770 [ThreadStatic]
3771 public static int Defsublines;
3772
3773 [ThreadStatic]
3774 public static int Defamplitude;
3775
3776 [ThreadStatic]
3777 public static int DefminDelay;
3778
3779 [ThreadStatic]
3780 public static int DefmaxDelay;
3781
3782 [ThreadStatic]
3783 public static int Defoffset;
3784
3785 [ThreadStatic]
3786 public static bool IsDebug;
3787
3788 [ThreadStatic]
3789 public static MouseEmulator.TypesStyleMouseMove MouseMoveStyle;
3790
3791 [ThreadStatic]
3792 public static bool UseInternalConsiderScrool;
3793
3794 private readonly static object Locker;
3795
3796 private readonly static object LockerInput;
3797
3798 public static bool ErrorDetected
3799 {
3800 get;
3801 private set;
3802 }
3803
3804 static MouseEmulator()
3805 {
3806 MouseEmulator.CurrentX = 0;
3807 MouseEmulator.CurrentY = 0;
3808 MouseEmulator.WorkTabHandle = 0;
3809 MouseEmulator.Defsublines = 5;
3810 MouseEmulator.Defamplitude = 10;
3811 MouseEmulator.DefminDelay = 2;
3812 MouseEmulator.DefmaxDelay = 5;
3813 MouseEmulator.Defoffset = 5;
3814 MouseEmulator.IsDebug = false;
3815 MouseEmulator.UseInternalConsiderScrool = true;
3816 MouseEmulator.Locker = new object();
3817 MouseEmulator.LockerInput = new object();
3818 }
3819
3820 public MouseEmulator()
3821 {
3822 }
3823
3824 public static string ActiveWindow(string name, bool topMost = false)
3825 {
3826 string str;
3827 lock (MouseEmulator.Locker)
3828 {
3829 str = Emulator.ActiveWindow(name, topMost);
3830 }
3831 return str;
3832 }
3833
3834 public static string ButtonClick(string windowName, string buttonName, bool topMost = false)
3835 {
3836 string str;
3837 lock (MouseEmulator.Locker)
3838 {
3839 str = Emulator.ButtonClick(windowName, buttonName, topMost);
3840 }
3841 return str;
3842 }
3843
3844 private static MouseEmulator.Vector2 CalcBezierCurve(MouseEmulator.Vector2[] pts, double t)
3845 {
3846 MouseEmulator.Vector2 vector2;
3847 try
3848 {
3849 double num = (1 - t) * (1 - t) * (1 - t);
3850 double num1 = (1 - t) * (1 - t) * 3 * t;
3851 double num2 = (1 - t) * t * 3 * t;
3852 double num3 = t * t * t;
3853 double x = num * pts[0].X + num1 * pts[1].X + num2 * pts[2].X + num3 * pts[3].X;
3854 double y = num * pts[0].Y + num1 * pts[1].Y + num2 * pts[2].Y + num3 * pts[3].Y;
3855 vector2 = new MouseEmulator.Vector2(x, y);
3856 }
3857 catch
3858 {
3859 MouseEmulator.ErrorDetected = true;
3860 vector2 = new MouseEmulator.Vector2(0, 0);
3861 }
3862 return vector2;
3863 }
3864
3865 public static string CloseWindow(string name)
3866 {
3867 string str;
3868 lock (MouseEmulator.Locker)
3869 {
3870 str = Emulator.CloseWindow(name);
3871 }
3872 return str;
3873 }
3874
3875 private static void DoLog(string Mess)
3876 {
3877 if (MouseEmulator.project != null)
3878 {
3879 MouseEmulator.project.SendInfoToLog(Mess, true);
3880 }
3881 }
3882
3883 public static string DragAndDrop(int handle, int fromX, int formY, int toX, int toY)
3884 {
3885 string str;
3886 lock (MouseEmulator.Locker)
3887 {
3888 str = Emulator.DragAndDrop(handle, fromX, formY, toX, toY);
3889 }
3890 return str;
3891 }
3892
3893 public static string FixedMouseMove(int handle, int x, int y)
3894 {
3895 string str;
3896 lock (MouseEmulator.Locker)
3897 {
3898 string message = "ok";
3899 MouseEmulator.ErrorDetected = false;
3900 try
3901 {
3902 if (MouseEmulator.IsDebug)
3903 {
3904 NativeMethods.RECT rECT = new NativeMethods.RECT();
3905 NativeMethods.GetWindowRect((IntPtr)handle, ref rECT);
3906 NativeMethods.SetCursorPos(rECT.Left + x, rECT.Top + y);
3907 }
3908 switch (MouseEmulator.MouseMoveStyle)
3909 {
3910 case MouseEmulator.TypesStyleMouseMove.SMM_winapi:
3911 {
3912 NativeMethods.PostMessage((IntPtr)handle, (IntPtr)512, IntPtr.Zero, (IntPtr)MouseEmulator.MAKELPARAM(x, y));
3913 break;
3914 }
3915 case MouseEmulator.TypesStyleMouseMove.SMM_InternalMouseMove:
3916 {
3917 if (MouseEmulator.instance == null)
3918 {
3919 break;
3920 }
3921 MouseEmulator.instance.ActiveTab.MouseMove(x, y, false, false);
3922 break;
3923 }
3924 case MouseEmulator.TypesStyleMouseMove.SMM_InternalMouseMoveFull:
3925 {
3926 if (MouseEmulator.instance == null)
3927 {
3928 break;
3929 }
3930 MouseEmulator.instance.ActiveTab.FullEmulationMouseSetOptions(0, 1, 2, 0.0001f, 0.0001f, 0.0001f);
3931 MouseEmulator.instance.ActiveTab.FullEmulationMouseMove(x, y);
3932 break;
3933 }
3934 }
3935 }
3936 catch (Exception exception1)
3937 {
3938 Exception exception = exception1;
3939 MouseEmulator.ErrorDetected = true;
3940 message = exception.Message;
3941 }
3942 str = message;
3943 }
3944 return str;
3945 }
3946
3947 private static Point GetRandomElementPoint(HtmlElement el, int offset = 3)
3948 {
3949 Random random = new Random();
3950 int num = Convert.ToInt32(el.GetAttribute("leftintab"));
3951 int num1 = Convert.ToInt32(el.GetAttribute("topintab"));
3952 int num2 = Convert.ToInt32(el.GetAttribute("width"));
3953 int num3 = Convert.ToInt32(el.GetAttribute("height"));
3954 int num4 = num + offset + random.Next(num2 - offset);
3955 int num5 = num1 + offset + random.Next(num3 - offset);
3956 return new Point(num4, num5);
3957 }
3958
3959 private static MouseEmulator.Vector2[] GetReperPoints(MouseEmulator.Vector2 startPoint, MouseEmulator.Vector2 endPoint, int amplitude)
3960 {
3961 MouseEmulator.Vector2[] vector2Array;
3962 try
3963 {
3964 double x = startPoint.X;
3965 double y = startPoint.Y;
3966 double num = endPoint.X;
3967 double y1 = endPoint.Y;
3968 MouseEmulator.Vector2 vector2 = new MouseEmulator.Vector2(x, y);
3969 MouseEmulator.Vector2 vector21 = new MouseEmulator.Vector2(num, y1);
3970 MouseEmulator.Vector2 vector22 = new MouseEmulator.Vector2((vector2.X + vector21.X) / 2, (vector2.Y + vector21.Y) / 2);
3971 MouseEmulator.Vector2 vector23 = new MouseEmulator.Vector2((vector2.X + vector22.X) / 2, (vector2.Y + vector22.Y) / 2);
3972 MouseEmulator.Vector2 vector24 = new MouseEmulator.Vector2((vector22.X + vector21.X) / 2, (vector22.Y + vector21.Y) / 2);
3973 Random random = new Random();
3974 vector23.X += (double)random.Next(-amplitude, amplitude);
3975 vector23.Y += (double)random.Next(-amplitude, amplitude);
3976 vector24.X += (double)random.Next(-amplitude, amplitude);
3977 vector24.Y += (double)random.Next(-amplitude, amplitude);
3978 vector2Array = new MouseEmulator.Vector2[] { vector2, vector23, vector24, vector21 };
3979 }
3980 catch
3981 {
3982 MouseEmulator.ErrorDetected = true;
3983 vector2Array = new MouseEmulator.Vector2[4];
3984 }
3985 return vector2Array;
3986 }
3987
3988 private static List<Point> GetSubLines(Point startPoint, Point endPoint, int diver)
3989 {
3990 List<Point> points;
3991 try
3992 {
3993 List<Point> points1 = new List<Point>();
3994 int x = 0;
3995 int y = 0;
3996 for (int i = 0; i <= diver; i++)
3997 {
3998 x = startPoint.X + i * ((endPoint.X - startPoint.X) / diver);
3999 y = startPoint.Y + i * ((endPoint.Y - startPoint.Y) / diver);
4000 points1.Add(new Point(x, y));
4001 }
4002 points = points1;
4003 }
4004 catch
4005 {
4006 MouseEmulator.ErrorDetected = true;
4007 points = new List<Point>();
4008 }
4009 return points;
4010 }
4011
4012 public static void HMClickLeft()
4013 {
4014 MouseEmulator.MouseClickNoFocus(MouseEmulator.WorkTabHandle, MouseButton.Left, MouseButtonEvent.Click, MouseEmulator.CurrentX, MouseEmulator.CurrentY);
4015 }
4016
4017 public static void HMClickRight()
4018 {
4019 MouseEmulator.MouseClickNoFocus(MouseEmulator.WorkTabHandle, MouseButton.Right, MouseButtonEvent.Click, MouseEmulator.CurrentX, MouseEmulator.CurrentY);
4020 }
4021
4022 public static void HMMoveExDef(HtmlElement endpointElement)
4023 {
4024 MouseEmulator.HumanMouseMoveEx(MouseEmulator.WorkTabHandle, endpointElement, MouseEmulator.Defsublines, MouseEmulator.Defamplitude, MouseEmulator.DefminDelay, MouseEmulator.DefmaxDelay, MouseEmulator.Defoffset);
4025 }
4026
4027 public static void HumanMouseMove(int handle, Point startPoint, Point endPoint, int amplitude, int minDelay, int maxDelay)
4028 {
4029 MouseEmulator.HumanMouseMoveIn(handle, startPoint, endPoint, amplitude, minDelay, maxDelay);
4030 if (MouseEmulator.CurrentX != endPoint.X || MouseEmulator.CurrentY != endPoint.Y)
4031 {
4032 MouseEmulator.HumanMouseMoveIn(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), endPoint, 2, minDelay, maxDelay);
4033 }
4034 }
4035
4036 public static void HumanMouseMove(int handle, Point endPoint, int amplitude, int minDelay, int maxDelay)
4037 {
4038 MouseEmulator.HumanMouseMoveIn(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), endPoint, amplitude, minDelay, maxDelay);
4039 if (MouseEmulator.CurrentX != endPoint.X || MouseEmulator.CurrentY != endPoint.Y)
4040 {
4041 MouseEmulator.HumanMouseMoveIn(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), endPoint, 2, minDelay, maxDelay);
4042 }
4043 }
4044
4045 public static void HumanMouseMove(int handle, Point startPoint, HtmlElement endpointElement, int amplitude, int minDelay, int maxDelay)
4046 {
4047 if (endpointElement.IsVoid)
4048 {
4049 MouseEmulator.ErrorDetected = true;
4050 return;
4051 }
4052 Point randomElementPoint = MouseEmulator.GetRandomElementPoint(endpointElement, 3);
4053 MouseEmulator.HumanMouseMoveIn(handle, startPoint, randomElementPoint, amplitude, minDelay, maxDelay);
4054 if (MouseEmulator.CurrentX != randomElementPoint.X || MouseEmulator.CurrentY != randomElementPoint.Y)
4055 {
4056 MouseEmulator.HumanMouseMoveIn(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), randomElementPoint, 2, minDelay, maxDelay);
4057 }
4058 }
4059
4060 public static void HumanMouseMove(int handle, HtmlElement endpointElement, int amplitude, int minDelay, int maxDelay)
4061 {
4062 MouseEmulator.HumanMouseMove(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), endpointElement, amplitude, minDelay, maxDelay);
4063 }
4064
4065 public static void HumanMouseMoveEx(int handle, Point startPoint, Point endPoint, int sublines, int amplitude, int minDelay, int maxDelay)
4066 {
4067 try
4068 {
4069 List<Point> subLines = MouseEmulator.GetSubLines(startPoint, endPoint, sublines);
4070 for (int i = 1; i < subLines.Count; i++)
4071 {
4072 MouseEmulator.HumanMouseMoveIn(handle, subLines[i - 1], subLines[i], amplitude, minDelay, maxDelay);
4073 }
4074 if (MouseEmulator.CurrentX != endPoint.X || MouseEmulator.CurrentY != endPoint.Y)
4075 {
4076 MouseEmulator.HumanMouseMoveIn(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), endPoint, amplitude, minDelay, maxDelay);
4077 }
4078 }
4079 catch
4080 {
4081 MouseEmulator.ErrorDetected = true;
4082 }
4083 }
4084
4085 public static void HumanMouseMoveEx(int handle, Point endPoint, int sublines, int amplitude, int minDelay, int maxDelay)
4086 {
4087 MouseEmulator.HumanMouseMoveEx(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), endPoint, sublines, amplitude, minDelay, maxDelay);
4088 }
4089
4090 public static void HumanMouseMoveEx(int handle, Point startPoint, HtmlElement endpointElement, int sublines, int amplitude, int minDelay, int maxDelay, int offset = 5)
4091 {
4092 if (endpointElement.IsVoid)
4093 {
4094 MouseEmulator.ErrorDetected = true;
4095 return;
4096 }
4097 Point randomElementPoint = MouseEmulator.GetRandomElementPoint(endpointElement, 3);
4098 MouseEmulator.HumanMouseMoveEx(handle, startPoint, randomElementPoint, sublines, amplitude, minDelay, maxDelay);
4099 }
4100
4101 public static void HumanMouseMoveEx(int handle, HtmlElement endpointElement, int sublines, int amplitude, int minDelay, int maxDelay, int offset = 5)
4102 {
4103 if (endpointElement.IsVoid)
4104 {
4105 MouseEmulator.ErrorDetected = true;
4106 return;
4107 }
4108 Point randomElementPoint = MouseEmulator.GetRandomElementPoint(endpointElement, 3);
4109 MouseEmulator.HumanMouseMoveEx(handle, new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY), randomElementPoint, sublines, amplitude, minDelay, maxDelay);
4110 }
4111
4112 private static void HumanMouseMoveIn(int handle, Point startPoint, Point endPoint, int amplitude, int minDelay, int maxDelay)
4113 {
4114 try
4115 {
4116 MouseEmulator.Vector2[] reperPoints = MouseEmulator.GetReperPoints(new MouseEmulator.Vector2((double)startPoint.X, (double)startPoint.Y), new MouseEmulator.Vector2((double)endPoint.X, (double)endPoint.Y), amplitude);
4117 List<MouseEmulator.Vector2> vector2s = new List<MouseEmulator.Vector2>();
4118 double num = 0.025;
4119 for (double i = 0; i < 1; i += num)
4120 {
4121 vector2s.Add(MouseEmulator.CalcBezierCurve(reperPoints, i));
4122 }
4123 List<Point> points = new List<Point>();
4124 List<int> nums = new List<int>();
4125 Random random = new Random();
4126 for (int j = 0; j < vector2s.Count; j++)
4127 {
4128 MouseEmulator.CurrentX = (int)Math.Round(vector2s[j].X);
4129 MouseEmulator.CurrentY = (int)Math.Round(vector2s[j].Y);
4130 if (MouseEmulator.MouseMoveStyle != MouseEmulator.TypesStyleMouseMove.SMM_InternalMouseMovePOINTS)
4131 {
4132 MouseEmulator.FixedMouseMove(handle, MouseEmulator.CurrentX, MouseEmulator.CurrentY);
4133 System.Threading.Thread.Sleep(random.Next(minDelay, maxDelay));
4134 }
4135 else
4136 {
4137 points.Add(new Point(MouseEmulator.CurrentX, MouseEmulator.CurrentY));
4138 nums.Add(random.Next(minDelay, maxDelay));
4139 }
4140 }
4141 if (MouseEmulator.MouseMoveStyle == MouseEmulator.TypesStyleMouseMove.SMM_InternalMouseMovePOINTS)
4142 {
4143 MouseEmulator.instance.ActiveTab.MouseMove(points.ToArray(), nums.ToArray(), false, false);
4144 }
4145 }
4146 catch
4147 {
4148 MouseEmulator.ErrorDetected = true;
4149 }
4150 }
4151
4152 public static void HumanMouseWheel(int handle, int SBWheelAction, bool isVertical = true)
4153 {
4154 if (isVertical)
4155 {
4156 NativeMethods.PostMessage((IntPtr)handle, (IntPtr)277, (IntPtr)SBWheelAction, IntPtr.Zero);
4157 return;
4158 }
4159 NativeMethods.PostMessage((IntPtr)handle, (IntPtr)276, (IntPtr)SBWheelAction, IntPtr.Zero);
4160 }
4161
4162 public static bool IsWindowExists(string name)
4163 {
4164 bool flag;
4165 lock (MouseEmulator.Locker)
4166 {
4167 flag = Emulator.IsWindowExists(name);
4168 }
4169 return flag;
4170 }
4171
4172 private static int MAKELPARAM(int p, int p_2)
4173 {
4174 return p & 65535 | p_2 << 16;
4175 }
4176
4177 private static int MAKEPARAM(int l, int h)
4178 {
4179 return l & 65535 | h << 16;
4180 }
4181
4182 public static string MaximizeWindow(string name, bool topMost = false)
4183 {
4184 string str;
4185 lock (MouseEmulator.Locker)
4186 {
4187 str = Emulator.MaximizeWindow(name, topMost);
4188 }
4189 return str;
4190 }
4191
4192 public static string MinimizeWindow(string name, bool topMost = false)
4193 {
4194 string str;
4195 lock (MouseEmulator.Locker)
4196 {
4197 str = Emulator.MinimizeWindow(name, topMost);
4198 }
4199 return str;
4200 }
4201
4202 public static string MouseClick(string windowName, MouseButton button, MouseButtonEvent buttonEvent, int x, int y, bool topMost = false)
4203 {
4204 string str;
4205 lock (MouseEmulator.Locker)
4206 {
4207 str = Emulator.MouseClick(windowName, button, buttonEvent, x, y, topMost);
4208 }
4209 return str;
4210 }
4211
4212 public static string MouseClick(int handle, MouseButton button, MouseButtonEvent buttonEvent, int x, int y)
4213 {
4214 string str;
4215 lock (MouseEmulator.Locker)
4216 {
4217 str = Emulator.MouseClick(handle, button, buttonEvent, x, y);
4218 }
4219 return str;
4220 }
4221
4222 public static void MouseClickLeft(int handle)
4223 {
4224 MouseEmulator.MouseClickNoFocus(handle, MouseButton.Left, MouseButtonEvent.Click, MouseEmulator.CurrentX, MouseEmulator.CurrentY);
4225 }
4226
4227 public static string MouseClickNoFocus(int handle, MouseButton button, MouseButtonEvent buttonEvent, int x, int y)
4228 {
4229 string str;
4230 lock (MouseEmulator.Locker)
4231 {
4232 string message = "ok";
4233 MouseEmulator.ErrorDetected = false;
4234 try
4235 {
4236 int num = 0;
4237 int num1 = 0;
4238 IntPtr zero = IntPtr.Zero;
4239 IntPtr intPtr = IntPtr.Zero;
4240 switch (buttonEvent)
4241 {
4242 case MouseButtonEvent.Down:
4243 {
4244 num = (button == MouseButton.Left ? 513 : 516);
4245 zero = (button == MouseButton.Left ? (IntPtr)1 : (IntPtr)2);
4246 num1 = 0;
4247 intPtr = IntPtr.Zero;
4248 break;
4249 }
4250 case MouseButtonEvent.Up:
4251 {
4252 num = (button == MouseButton.Left ? 514 : 517);
4253 zero = (button == MouseButton.Left ? (IntPtr)1 : (IntPtr)2);
4254 num1 = 0;
4255 intPtr = IntPtr.Zero;
4256 break;
4257 }
4258 case MouseButtonEvent.Click:
4259 {
4260 num = (button == MouseButton.Left ? 513 : 516);
4261 zero = (button == MouseButton.Left ? (IntPtr)1 : (IntPtr)2);
4262 num1 = (button == MouseButton.Left ? 514 : 517);
4263 intPtr = (button == MouseButton.Left ? (IntPtr)1 : (IntPtr)2);
4264 break;
4265 }
4266 }
4267 if (num1 != 0)
4268 {
4269 NativeMethods.PostMessage((IntPtr)handle, (IntPtr)num, zero, (IntPtr)(y << 16 | x));
4270 NativeMethods.PostMessage((IntPtr)handle, (IntPtr)num1, intPtr, (IntPtr)(y << 16 | x));
4271 }
4272 else
4273 {
4274 NativeMethods.PostMessage((IntPtr)handle, (IntPtr)num, zero, (IntPtr)(y << 16 | x));
4275 }
4276 }
4277 catch (Exception exception1)
4278 {
4279 Exception exception = exception1;
4280 MouseEmulator.ErrorDetected = true;
4281 message = exception.Message;
4282 }
4283 str = message;
4284 }
4285 return str;
4286 }
4287
4288 public static void MouseClickRight(int handle)
4289 {
4290 MouseEmulator.MouseClickNoFocus(handle, MouseButton.Right, MouseButtonEvent.Click, MouseEmulator.CurrentX, MouseEmulator.CurrentY);
4291 }
4292
4293 public static string MouseMove(string windowName, int x, int y, bool topMost = false)
4294 {
4295 string str;
4296 lock (MouseEmulator.Locker)
4297 {
4298 str = Emulator.MouseMove(windowName, x, y, topMost);
4299 }
4300 return str;
4301 }
4302
4303 public static string MouseMove(int handle, int x, int y)
4304 {
4305 string str;
4306 lock (MouseEmulator.Locker)
4307 {
4308 str = Emulator.MouseMove(handle, x, y);
4309 }
4310 return str;
4311 }
4312
4313 public static void SendChar(int handle, char ch, int minDelay, int maxDelay)
4314 {
4315 lock (MouseEmulator.LockerInput)
4316 {
4317 Random random = new Random();
4318 NativeMethods.SetForegroundWindow((IntPtr)handle);
4319 NativeMethods.SetActiveWindow((IntPtr)handle);
4320 if (char.IsUpper(ch))
4321 {
4322 NativeMethods.SimulateKeyDown(handle, VirtualKeyCode.SHIFT);
4323 System.Threading.Thread.Sleep(random.Next(minDelay, maxDelay));
4324 }
4325 INPUT nPUT = new INPUT()
4326 {
4327 Type = 1
4328 };
4329 nPUT.Data.Keyboard = new KEYBDINPUT()
4330 {
4331 KeyCode = 0,
4332 Scan = ch,
4333 Flags = 4,
4334 Time = 50,
4335 ExtraInfo = NativeMethods.GetMessageExtraInfo()
4336 };
4337 INPUT[] nPUTArray = new INPUT[] { nPUT };
4338 if (NativeMethods.SendInput(1, nPUTArray, Marshal.SizeOf(typeof(INPUT))) == 0)
4339 {
4340 throw new Exception(string.Format("The key down simulation for {0} was not successful.", ch));
4341 }
4342 System.Threading.Thread.Sleep(random.Next(minDelay, maxDelay));
4343 nPUT = new INPUT()
4344 {
4345 Type = 1
4346 };
4347 nPUT.Data.Keyboard = new KEYBDINPUT()
4348 {
4349 KeyCode = 0,
4350 Scan = ch,
4351 Flags = 6,
4352 Time = 50,
4353 ExtraInfo = NativeMethods.GetMessageExtraInfo()
4354 };
4355 INPUT[] nPUTArray1 = new INPUT[] { nPUT };
4356 if (NativeMethods.SendInput(1, nPUTArray1, Marshal.SizeOf(typeof(INPUT))) == 0)
4357 {
4358 throw new Exception(string.Format("The key down simulation for {0} was not successful.", ch));
4359 }
4360 if (char.IsUpper(ch))
4361 {
4362 NativeMethods.SimulateKeyUp(handle, VirtualKeyCode.SHIFT);
4363 System.Threading.Thread.Sleep(random.Next(minDelay, maxDelay));
4364 }
4365 }
4366 }
4367
4368 public static void SendChar2(int handle, char ch, int minDelay, int maxDelay)
4369 {
4370 lock (MouseEmulator.LockerInput)
4371 {
4372 Random random = new Random();
4373 NativeMethods.SetForegroundWindow((IntPtr)handle);
4374 NativeMethods.SetActiveWindow((IntPtr)handle);
4375 if (char.IsUpper(ch))
4376 {
4377 NativeMethods.SimulateKeyDown(handle, VirtualKeyCode.SHIFT);
4378 System.Threading.Thread.Sleep(random.Next(minDelay, maxDelay));
4379 }
4380 NativeMethods.SimulateKeyDown(handle, NativeMethods.ConvertCharToVirtualKey(ch));
4381 System.Threading.Thread.Sleep(random.Next(minDelay, maxDelay));
4382 NativeMethods.SimulateKeyUp(handle, NativeMethods.ConvertCharToVirtualKey(ch));
4383 if (char.IsUpper(ch))
4384 {
4385 NativeMethods.SimulateKeyUp(handle, VirtualKeyCode.SHIFT);
4386 System.Threading.Thread.Sleep(random.Next(minDelay, maxDelay));
4387 }
4388 }
4389 }
4390
4391 public static void SendInput(int handle, string aText, int minDelay, int maxDelay)
4392 {
4393 lock (MouseEmulator.Locker)
4394 {
4395 try
4396 {
4397 Random random = new Random();
4398 string str = aText;
4399 for (int i = 0; i < str.Length; i++)
4400 {
4401 MouseEmulator.SendChar(handle, str[i], minDelay, maxDelay);
4402 }
4403 }
4404 catch (Exception exception)
4405 {
4406 MouseEmulator.ErrorDetected = true;
4407 }
4408 }
4409 }
4410
4411 public static void SendInput2(int handle, string aText, int minDelay, int maxDelay, string uselang)
4412 {
4413 lock (MouseEmulator.Locker)
4414 {
4415 try
4416 {
4417 Random random = new Random();
4418 NativeMethods.SetLang(handle, uselang);
4419 string str = aText;
4420 for (int i = 0; i < str.Length; i++)
4421 {
4422 MouseEmulator.SendChar2(handle, str[i], minDelay, maxDelay);
4423 }
4424 }
4425 catch (Exception exception)
4426 {
4427 MouseEmulator.ErrorDetected = true;
4428 }
4429 }
4430 }
4431
4432 public static string SendKey(int handle, System.Windows.Forms.Keys key, KeyboardEvent keyboardEvent)
4433 {
4434 string str;
4435 lock (MouseEmulator.Locker)
4436 {
4437 str = Emulator.SendKey(handle, key, keyboardEvent);
4438 }
4439 return str;
4440 }
4441
4442 public static string SendKey(string windowName, int x, int y, System.Windows.Forms.Keys key, KeyboardEvent keyboardEvent, bool topMost = false)
4443 {
4444 string str;
4445 lock (MouseEmulator.Locker)
4446 {
4447 str = Emulator.SendKey(windowName, x, y, key, keyboardEvent, topMost);
4448 }
4449 return str;
4450 }
4451
4452 public static string SendText(int handle, string text)
4453 {
4454 string str;
4455 lock (MouseEmulator.Locker)
4456 {
4457 str = Emulator.SendText(handle, text);
4458 }
4459 return str;
4460 }
4461
4462 public static string SendText(string windowName, int x, int y, string text, bool topMost = false)
4463 {
4464 string str;
4465 lock (MouseEmulator.Locker)
4466 {
4467 str = Emulator.SendText(windowName, x, y, text, topMost);
4468 }
4469 return str;
4470 }
4471
4472 public static void SetDefaultMoveSettings(int sublines, int amplitude, int minDelay, int maxDelay, int offset)
4473 {
4474 MouseEmulator.Defsublines = sublines;
4475 MouseEmulator.Defamplitude = amplitude;
4476 MouseEmulator.DefminDelay = minDelay;
4477 MouseEmulator.DefmaxDelay = maxDelay;
4478 MouseEmulator.Defoffset = offset;
4479 }
4480
4481 public static void SetDefaultTabHandle(int ActiveTabHandle)
4482 {
4483 MouseEmulator.WorkTabHandle = ActiveTabHandle;
4484 }
4485
4486 public static void SetStartCursorPos(int X, int Y)
4487 {
4488 MouseEmulator.CurrentX = X;
4489 MouseEmulator.CurrentY = Y;
4490 }
4491
4492 public struct SBWheel
4493 {
4494 public const int SB_LINEUP = 0;
4495
4496 public const int SB_LINELEFT = 0;
4497
4498 public const int SB_LINEDOWN = 1;
4499
4500 public const int SB_LINERIGHT = 1;
4501
4502 public const int SB_PAGEUP = 2;
4503
4504 public const int SB_PAGELEFT = 2;
4505
4506 public const int SB_PAGEDOWN = 3;
4507
4508 public const int SB_PAGERIGTH = 3;
4509
4510 public const int SB_PAGETOP = 6;
4511
4512 public const int SB_LEFT = 6;
4513
4514 public const int SB_PAGEBOTTOM = 7;
4515
4516 public const int SB_RIGHT = 7;
4517
4518 public const int SB_ENDSCROLL = 8;
4519 }
4520
4521 public enum TypesStyleMouseMove
4522 {
4523 SMM_winapi,
4524 SMM_InternalMouseMove,
4525 SMM_InternalMouseMoveFull,
4526 SMM_InternalMouseMovePOINTS
4527 }
4528
4529 private class Vector2
4530 {
4531 public double X;
4532
4533 public double Y;
4534
4535 public Vector2(double x, double y)
4536 {
4537 this.X = x;
4538 this.Y = y;
4539 }
4540 }
4541 }
4542}
4543
4544namespace MouseEmulation.Native
4545{
4546
4547 public struct HARDWAREINPUT
4548 {
4549 public uint Msg;
4550
4551 public ushort ParamL;
4552
4553 public ushort ParamH;
4554 }
4555
4556 public struct INPUT
4557 {
4558 public uint Type;
4559
4560 public MOUSEKEYBDHARDWAREINPUT Data;
4561 }
4562
4563 public enum InputType : uint
4564 {
4565 Mouse,
4566 Keyboard,
4567 Hardware
4568 }
4569
4570 public struct KEYBDINPUT
4571 {
4572 public ushort KeyCode;
4573
4574 public ushort Scan;
4575
4576 public uint Flags;
4577
4578 public uint Time;
4579
4580 public IntPtr ExtraInfo;
4581 }
4582
4583 [Flags]
4584 public enum KeyboardFlag : uint
4585 {
4586 ExtendedKey = 1,
4587 KeyUp = 2,
4588 Unicode = 4,
4589 ScanCode = 8
4590 }
4591
4592 [Flags]
4593 public enum MouseFlag : uint
4594 {
4595 Move = 1,
4596 LeftDown = 2,
4597 LeftUp = 4,
4598 RightDown = 8,
4599 RightUp = 16,
4600 MiddleDown = 32,
4601 MiddleUp = 64,
4602 XDown = 128,
4603 XUp = 256,
4604 VerticalWheel = 2048,
4605 HorizontalWheel = 4096,
4606 VirtualDesk = 16384,
4607 Absolute = 32768
4608 }
4609
4610 public struct MOUSEINPUT
4611 {
4612 public int X;
4613
4614 public int Y;
4615
4616 public uint MouseData;
4617
4618 public uint Flags;
4619
4620 public uint Time;
4621
4622 public IntPtr ExtraInfo;
4623 }
4624
4625 [StructLayout(LayoutKind.Explicit)]
4626 public struct MOUSEKEYBDHARDWAREINPUT
4627 {
4628 [FieldOffset(0)]
4629 public MOUSEINPUT Mouse;
4630
4631 [FieldOffset(0)]
4632 public KEYBDINPUT Keyboard;
4633
4634 [FieldOffset(0)]
4635 public HARDWAREINPUT Hardware;
4636 }
4637
4638 public static class NativeMethods
4639 {
4640 public const uint KEYEVENTF_EXTENDEDKEY = 1;
4641
4642 public const uint KEYEVENTF_KEYUP = 2;
4643
4644 public const uint KEYEVENTF_UNICODE = 4;
4645
4646 public const uint KEYEVENTF_SCANCODE = 8;
4647
4648 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
4649 public static extern IntPtr ChildWindowFromPoint(IntPtr hWndParent, Point nPoint);
4650
4651 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
4652 public static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint);
4653
4654 public static VirtualKeyCode ConvertCharToVirtualKey(char ch)
4655 {
4656 short num = NativeMethods.VkKeyScan(ch);
4657 System.Windows.Forms.Keys key = (System.Windows.Forms.Keys)(num & 255);
4658 int num1 = num >> 8;
4659 if ((num1 & 1) != 0)
4660 {
4661 key |= System.Windows.Forms.Keys.Shift;
4662 }
4663 if ((num1 & 2) != 0)
4664 {
4665 key |= System.Windows.Forms.Keys.Control;
4666 }
4667 if ((num1 & 4) != 0)
4668 {
4669 key |= System.Windows.Forms.Keys.Alt;
4670 }
4671 return (VirtualKeyCode)key;
4672 }
4673
4674 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
4675 public static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
4676
4677 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)]
4678 public static extern short GetAsyncKeyState(ushort virtualKeyCode);
4679
4680 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
4681 public static extern bool GetKeyboardState(byte[] lpKeyState);
4682
4683 public static IntPtr GetKeyCode(System.Windows.Forms.Keys key)
4684 {
4685 if (key > System.Windows.Forms.Keys.RControlKey)
4686 {
4687 if (key == System.Windows.Forms.Keys.Shift)
4688 {
4689 return (IntPtr)16;
4690 }
4691 if (key == System.Windows.Forms.Keys.Control)
4692 {
4693 return (IntPtr)17;
4694 }
4695 if (key == System.Windows.Forms.Keys.Alt)
4696 {
4697 return (IntPtr)18;
4698 }
4699 }
4700 else
4701 {
4702 switch (key)
4703 {
4704 case System.Windows.Forms.Keys.Back:
4705 {
4706 return (IntPtr)8;
4707 }
4708 case System.Windows.Forms.Keys.Tab:
4709 {
4710 return (IntPtr)9;
4711 }
4712 case System.Windows.Forms.Keys.LineFeed:
4713 case System.Windows.Forms.Keys.LButton | System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.Cancel | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.Tab | System.Windows.Forms.Keys.LineFeed:
4714 case System.Windows.Forms.Keys.Clear:
4715 case System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.XButton2 | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.Clear:
4716 case System.Windows.Forms.Keys.LButton | System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.Cancel | System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.XButton1 | System.Windows.Forms.Keys.XButton2 | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.Tab | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.Clear | System.Windows.Forms.Keys.Return | System.Windows.Forms.Keys.Enter:
4717 case System.Windows.Forms.Keys.ShiftKey:
4718 case System.Windows.Forms.Keys.ControlKey:
4719 case System.Windows.Forms.Keys.Menu:
4720 case System.Windows.Forms.Keys.Pause:
4721 case System.Windows.Forms.Keys.KanaMode:
4722 case System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.XButton2 | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.Menu | System.Windows.Forms.Keys.Capital | System.Windows.Forms.Keys.CapsLock:
4723 case System.Windows.Forms.Keys.JunjaMode:
4724 case System.Windows.Forms.Keys.FinalMode:
4725 case System.Windows.Forms.Keys.HanjaMode:
4726 case System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.Menu | System.Windows.Forms.Keys.FinalMode:
4727 case System.Windows.Forms.Keys.IMEConvert:
4728 case System.Windows.Forms.Keys.IMENonconvert:
4729 case System.Windows.Forms.Keys.IMEAccept:
4730 case System.Windows.Forms.Keys.IMEModeChange:
4731 case System.Windows.Forms.Keys.Select:
4732 case System.Windows.Forms.Keys.Print:
4733 case System.Windows.Forms.Keys.Execute:
4734 case System.Windows.Forms.Keys.Snapshot:
4735 case System.Windows.Forms.Keys.Help:
4736 case System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.Menu | System.Windows.Forms.Keys.FinalMode | System.Windows.Forms.Keys.Space | System.Windows.Forms.Keys.Next | System.Windows.Forms.Keys.PageDown | System.Windows.Forms.Keys.Down | System.Windows.Forms.Keys.Print | System.Windows.Forms.Keys.D0 | System.Windows.Forms.Keys.D2 | System.Windows.Forms.Keys.D8:
4737 case System.Windows.Forms.Keys.LButton | System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.Cancel | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.Tab | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.ControlKey | System.Windows.Forms.Keys.Menu | System.Windows.Forms.Keys.Pause | System.Windows.Forms.Keys.FinalMode | System.Windows.Forms.Keys.HanjaMode | System.Windows.Forms.Keys.KanjiMode | System.Windows.Forms.Keys.Escape | System.Windows.Forms.Keys.Space | System.Windows.Forms.Keys.Prior | System.Windows.Forms.Keys.PageUp | System.Windows.Forms.Keys.Next | System.Windows.Forms.Keys.PageDown | System.Windows.Forms.Keys.End | System.Windows.Forms.Keys.Down | System.Windows.Forms.Keys.Select | System.Windows.Forms.Keys.Print | System.Windows.Forms.Keys.Execute | System.Windows.Forms.Keys.D0 | System.Windows.Forms.Keys.D1 | System.Windows.Forms.Keys.D2 | System.Windows.Forms.Keys.D3 | System.Windows.Forms.Keys.D8 | System.Windows.Forms.Keys.D9:
4738 case System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.Clear | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.Capital | System.Windows.Forms.Keys.CapsLock | System.Windows.Forms.Keys.FinalMode | System.Windows.Forms.Keys.IMEConvert | System.Windows.Forms.Keys.Space | System.Windows.Forms.Keys.Home | System.Windows.Forms.Keys.Down | System.Windows.Forms.Keys.Snapshot | System.Windows.Forms.Keys.PrintScreen | System.Windows.Forms.Keys.D0 | System.Windows.Forms.Keys.D4 | System.Windows.Forms.Keys.D8:
4739 case System.Windows.Forms.Keys.LButton | System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.XButton1 | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.Tab | System.Windows.Forms.Keys.Clear | System.Windows.Forms.Keys.Return | System.Windows.Forms.Keys.Enter | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.ControlKey | System.Windows.Forms.Keys.Capital | System.Windows.Forms.Keys.CapsLock | System.Windows.Forms.Keys.KanaMode | System.Windows.Forms.Keys.HanguelMode | System.Windows.Forms.Keys.HangulMode | System.Windows.Forms.Keys.FinalMode | System.Windows.Forms.Keys.HanjaMode | System.Windows.Forms.Keys.KanjiMode | System.Windows.Forms.Keys.IMEConvert | System.Windows.Forms.Keys.IMENonconvert | System.Windows.Forms.Keys.Space | System.Windows.Forms.Keys.Prior | System.Windows.Forms.Keys.PageUp | System.Windows.Forms.Keys.Home | System.Windows.Forms.Keys.Left | System.Windows.Forms.Keys.Down | System.Windows.Forms.Keys.Select | System.Windows.Forms.Keys.Snapshot | System.Windows.Forms.Keys.PrintScreen | System.Windows.Forms.Keys.Insert | System.Windows.Forms.Keys.D0 | System.Windows.Forms.Keys.D1 | System.Windows.Forms.Keys.D4 | System.Windows.Forms.Keys.D5 | System.Windows.Forms.Keys.D8 | System.Windows.Forms.Keys.D9:
4740 case System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.XButton2 | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.Clear | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.Menu | System.Windows.Forms.Keys.Capital | System.Windows.Forms.Keys.CapsLock | System.Windows.Forms.Keys.FinalMode | System.Windows.Forms.Keys.IMEConvert | System.Windows.Forms.Keys.IMEAccept | System.Windows.Forms.Keys.IMEAceept | System.Windows.Forms.Keys.Space | System.Windows.Forms.Keys.Next | System.Windows.Forms.Keys.PageDown | System.Windows.Forms.Keys.Home | System.Windows.Forms.Keys.Up | System.Windows.Forms.Keys.Down | System.Windows.Forms.Keys.Print | System.Windows.Forms.Keys.Snapshot | System.Windows.Forms.Keys.PrintScreen | System.Windows.Forms.Keys.Delete | System.Windows.Forms.Keys.D0 | System.Windows.Forms.Keys.D2 | System.Windows.Forms.Keys.D4 | System.Windows.Forms.Keys.D6 | System.Windows.Forms.Keys.D8:
4741 case System.Windows.Forms.Keys.LButton | System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.Cancel | System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.XButton1 | System.Windows.Forms.Keys.XButton2 | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.Tab | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.Clear | System.Windows.Forms.Keys.Return | System.Windows.Forms.Keys.Enter | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.ControlKey | System.Windows.Forms.Keys.Menu | System.Windows.Forms.Keys.Pause | System.Windows.Forms.Keys.Capital | System.Windows.Forms.Keys.CapsLock | System.Windows.Forms.Keys.KanaMode | System.Windows.Forms.Keys.HanguelMode | System.Windows.Forms.Keys.HangulMode | System.Windows.Forms.Keys.JunjaMode | System.Windows.Forms.Keys.FinalMode | System.Windows.Forms.Keys.HanjaMode | System.Windows.Forms.Keys.KanjiMode | System.Windows.Forms.Keys.Escape | System.Windows.Forms.Keys.IMEConvert | System.Windows.Forms.Keys.IMENonconvert | System.Windows.Forms.Keys.IMEAccept | System.Windows.Forms.Keys.IMEAceept | System.Windows.Forms.Keys.IMEModeChange | System.Windows.Forms.Keys.Space | System.Windows.Forms.Keys.Prior | System.Windows.Forms.Keys.PageUp | System.Windows.Forms.Keys.Next | System.Windows.Forms.Keys.PageDown | System.Windows.Forms.Keys.End | System.Windows.Forms.Keys.Home | System.Windows.Forms.Keys.Left | System.Windows.Forms.Keys.Up | System.Windows.Forms.Keys.Right | System.Windows.Forms.Keys.Down | System.Windows.Forms.Keys.Select | System.Windows.Forms.Keys.Print | System.Windows.Forms.Keys.Execute | System.Windows.Forms.Keys.Snapshot | System.Windows.Forms.Keys.PrintScreen | System.Windows.Forms.Keys.Insert | System.Windows.Forms.Keys.Delete | System.Windows.Forms.Keys.Help | System.Windows.Forms.Keys.D0 | System.Windows.Forms.Keys.D1 | System.Windows.Forms.Keys.D2 | System.Windows.Forms.Keys.D3 | System.Windows.Forms.Keys.D4 | System.Windows.Forms.Keys.D5 | System.Windows.Forms.Keys.D6 | System.Windows.Forms.Keys.D7 | System.Windows.Forms.Keys.D8 | System.Windows.Forms.Keys.D9:
4742 //case 64:
4743 case System.Windows.Forms.Keys.LWin:
4744 case System.Windows.Forms.Keys.RWin:
4745 case System.Windows.Forms.Keys.Apps:
4746 case System.Windows.Forms.Keys.RButton | System.Windows.Forms.Keys.MButton | System.Windows.Forms.Keys.XButton2 | System.Windows.Forms.Keys.Back | System.Windows.Forms.Keys.LineFeed | System.Windows.Forms.Keys.Clear | System.Windows.Forms.Keys.ShiftKey | System.Windows.Forms.Keys.Menu | System.Windows.Forms.Keys.Capital | System.Windows.Forms.Keys.CapsLock | System.Windows.Forms.Keys.FinalMode | System.Windows.Forms.Keys.IMEConvert | System.Windows.Forms.Keys.IMEAccept | System.Windows.Forms.Keys.IMEAceept | System.Windows.Forms.Keys.B | System.Windows.Forms.Keys.D | System.Windows.Forms.Keys.F | System.Windows.Forms.Keys.H | System.Windows.Forms.Keys.J | System.Windows.Forms.Keys.L | System.Windows.Forms.Keys.N | System.Windows.Forms.Keys.P | System.Windows.Forms.Keys.R | System.Windows.Forms.Keys.T | System.Windows.Forms.Keys.V | System.Windows.Forms.Keys.X | System.Windows.Forms.Keys.Z | System.Windows.Forms.Keys.RWin:
4747 case System.Windows.Forms.Keys.Sleep:
4748 case System.Windows.Forms.Keys.Multiply:
4749 case System.Windows.Forms.Keys.Separator:
4750 case System.Windows.Forms.Keys.Decimal:
4751 case System.Windows.Forms.Keys.Divide:
4752 {
4753 break;
4754 }
4755 case System.Windows.Forms.Keys.Return:
4756 {
4757 return (IntPtr)13;
4758 }
4759 case System.Windows.Forms.Keys.Capital:
4760 {
4761 return (IntPtr)20;
4762 }
4763 case System.Windows.Forms.Keys.Escape:
4764 {
4765 return (IntPtr)27;
4766 }
4767 case System.Windows.Forms.Keys.Space:
4768 {
4769 return (IntPtr)32;
4770 }
4771 case System.Windows.Forms.Keys.Prior:
4772 {
4773 return (IntPtr)33;
4774 }
4775 case System.Windows.Forms.Keys.Next:
4776 {
4777 return (IntPtr)34;
4778 }
4779 case System.Windows.Forms.Keys.End:
4780 {
4781 return (IntPtr)35;
4782 }
4783 case System.Windows.Forms.Keys.Home:
4784 {
4785 return (IntPtr)36;
4786 }
4787 case System.Windows.Forms.Keys.Left:
4788 {
4789 return (IntPtr)37;
4790 }
4791 case System.Windows.Forms.Keys.Up:
4792 {
4793 return (IntPtr)38;
4794 }
4795 case System.Windows.Forms.Keys.Right:
4796 {
4797 return (IntPtr)39;
4798 }
4799 case System.Windows.Forms.Keys.Down:
4800 {
4801 return (IntPtr)40;
4802 }
4803 case System.Windows.Forms.Keys.Insert:
4804 {
4805 return (IntPtr)45;
4806 }
4807 case System.Windows.Forms.Keys.Delete:
4808 {
4809 return (IntPtr)46;
4810 }
4811 case System.Windows.Forms.Keys.D0:
4812 {
4813 return (IntPtr)48;
4814 }
4815 case System.Windows.Forms.Keys.D1:
4816 {
4817 return (IntPtr)49;
4818 }
4819 case System.Windows.Forms.Keys.D2:
4820 {
4821 return (IntPtr)50;
4822 }
4823 case System.Windows.Forms.Keys.D3:
4824 {
4825 return (IntPtr)51;
4826 }
4827 case System.Windows.Forms.Keys.D4:
4828 {
4829 return (IntPtr)52;
4830 }
4831 case System.Windows.Forms.Keys.D5:
4832 {
4833 return (IntPtr)53;
4834 }
4835 case System.Windows.Forms.Keys.D6:
4836 {
4837 return (IntPtr)54;
4838 }
4839 case System.Windows.Forms.Keys.D7:
4840 {
4841 return (IntPtr)55;
4842 }
4843 case System.Windows.Forms.Keys.D8:
4844 {
4845 return (IntPtr)56;
4846 }
4847 case System.Windows.Forms.Keys.D9:
4848 {
4849 return (IntPtr)57;
4850 }
4851 case System.Windows.Forms.Keys.A:
4852 {
4853 return (IntPtr)65;
4854 }
4855 case System.Windows.Forms.Keys.B:
4856 {
4857 return (IntPtr)66;
4858 }
4859 case System.Windows.Forms.Keys.C:
4860 {
4861 return (IntPtr)67;
4862 }
4863 case System.Windows.Forms.Keys.D:
4864 {
4865 return (IntPtr)68;
4866 }
4867 case System.Windows.Forms.Keys.E:
4868 {
4869 return (IntPtr)69;
4870 }
4871 case System.Windows.Forms.Keys.F:
4872 {
4873 return (IntPtr)70;
4874 }
4875 case System.Windows.Forms.Keys.G:
4876 {
4877 return (IntPtr)71;
4878 }
4879 case System.Windows.Forms.Keys.H:
4880 {
4881 return (IntPtr)72;
4882 }
4883 case System.Windows.Forms.Keys.I:
4884 {
4885 return (IntPtr)73;
4886 }
4887 case System.Windows.Forms.Keys.J:
4888 {
4889 return (IntPtr)74;
4890 }
4891 case System.Windows.Forms.Keys.K:
4892 {
4893 return (IntPtr)75;
4894 }
4895 case System.Windows.Forms.Keys.L:
4896 {
4897 return (IntPtr)76;
4898 }
4899 case System.Windows.Forms.Keys.M:
4900 {
4901 return (IntPtr)77;
4902 }
4903 case System.Windows.Forms.Keys.N:
4904 {
4905 return (IntPtr)78;
4906 }
4907 case System.Windows.Forms.Keys.O:
4908 {
4909 return (IntPtr)79;
4910 }
4911 case System.Windows.Forms.Keys.P:
4912 {
4913 return (IntPtr)80;
4914 }
4915 case System.Windows.Forms.Keys.Q:
4916 {
4917 return (IntPtr)81;
4918 }
4919 case System.Windows.Forms.Keys.R:
4920 {
4921 return (IntPtr)82;
4922 }
4923 case System.Windows.Forms.Keys.S:
4924 {
4925 return (IntPtr)83;
4926 }
4927 case System.Windows.Forms.Keys.T:
4928 {
4929 return (IntPtr)84;
4930 }
4931 case System.Windows.Forms.Keys.U:
4932 {
4933 return (IntPtr)85;
4934 }
4935 case System.Windows.Forms.Keys.V:
4936 {
4937 return (IntPtr)86;
4938 }
4939 case System.Windows.Forms.Keys.W:
4940 {
4941 return (IntPtr)87;
4942 }
4943 case System.Windows.Forms.Keys.X:
4944 {
4945 return (IntPtr)88;
4946 }
4947 case System.Windows.Forms.Keys.Y:
4948 {
4949 return (IntPtr)89;
4950 }
4951 case System.Windows.Forms.Keys.Z:
4952 {
4953 return (IntPtr)90;
4954 }
4955 case System.Windows.Forms.Keys.NumPad0:
4956 {
4957 return (IntPtr)96;
4958 }
4959 case System.Windows.Forms.Keys.NumPad1:
4960 {
4961 return (IntPtr)97;
4962 }
4963 case System.Windows.Forms.Keys.NumPad2:
4964 {
4965 return (IntPtr)98;
4966 }
4967 case System.Windows.Forms.Keys.NumPad3:
4968 {
4969 return (IntPtr)99;
4970 }
4971 case System.Windows.Forms.Keys.NumPad4:
4972 {
4973 return (IntPtr)100;
4974 }
4975 case System.Windows.Forms.Keys.NumPad5:
4976 {
4977 return (IntPtr)101;
4978 }
4979 case System.Windows.Forms.Keys.NumPad6:
4980 {
4981 return (IntPtr)102;
4982 }
4983 case System.Windows.Forms.Keys.NumPad7:
4984 {
4985 return (IntPtr)103;
4986 }
4987 case System.Windows.Forms.Keys.NumPad8:
4988 {
4989 return (IntPtr)104;
4990 }
4991 case System.Windows.Forms.Keys.NumPad9:
4992 {
4993 return (IntPtr)105;
4994 }
4995 case System.Windows.Forms.Keys.Add:
4996 {
4997 return (IntPtr)187;
4998 }
4999 case System.Windows.Forms.Keys.Subtract:
5000 {
5001 return (IntPtr)189;
5002 }
5003 case System.Windows.Forms.Keys.F1:
5004 {
5005 return (IntPtr)112;
5006 }
5007 case System.Windows.Forms.Keys.F2:
5008 {
5009 return (IntPtr)113;
5010 }
5011 case System.Windows.Forms.Keys.F3:
5012 {
5013 return (IntPtr)114;
5014 }
5015 case System.Windows.Forms.Keys.F4:
5016 {
5017 return (IntPtr)115;
5018 }
5019 case System.Windows.Forms.Keys.F5:
5020 {
5021 return (IntPtr)116;
5022 }
5023 case System.Windows.Forms.Keys.F6:
5024 {
5025 return (IntPtr)117;
5026 }
5027 case System.Windows.Forms.Keys.F7:
5028 {
5029 return (IntPtr)118;
5030 }
5031 case System.Windows.Forms.Keys.F8:
5032 {
5033 return (IntPtr)119;
5034 }
5035 case System.Windows.Forms.Keys.F9:
5036 {
5037 return (IntPtr)120;
5038 }
5039 case System.Windows.Forms.Keys.F10:
5040 {
5041 return (IntPtr)121;
5042 }
5043 default:
5044 {
5045 switch (key)
5046 {
5047 case System.Windows.Forms.Keys.LControlKey:
5048 {
5049 return (IntPtr)162;
5050 }
5051 case System.Windows.Forms.Keys.RControlKey:
5052 {
5053 return (IntPtr)163;
5054 }
5055 }
5056 break;
5057 }
5058 }
5059 }
5060 return (IntPtr)0;
5061 }
5062
5063 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)]
5064 public static extern short GetKeyState(ushort virtualKeyCode);
5065
5066 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5067 public static extern IntPtr GetMessageExtraInfo();
5068
5069 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)]
5070 public static extern bool GetWindowRect(IntPtr hWnd, ref NativeMethods.RECT lpRect);
5071
5072 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5073 public static extern int LoadKeyboardLayout(string pwszKLID, uint Flags);
5074
5075 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5076 public static extern int MapVirtualKey(int uCode, uint uMapType);
5077
5078 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5079 public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
5080
5081 [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=false)]
5082 public static extern IntPtr PostMessage(IntPtr hWnd, IntPtr Msg, IntPtr wParam, IntPtr lParam);
5083
5084 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)]
5085 public static extern uint SendInput(uint numberOfInputs, INPUT[] inputs, int sizeOfInputStructure);
5086
5087 [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=false)]
5088 public static extern IntPtr SendMessage(IntPtr hWnd, IntPtr Msg, IntPtr wParam, IntPtr lParam);
5089
5090 [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
5091 public static extern int SetActiveWindow(IntPtr hWnd);
5092
5093 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false, SetLastError=true)]
5094 public static extern bool SetCursorPos(int x, int y);
5095
5096 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5097 public static extern int SetForegroundWindow(IntPtr hWnd);
5098
5099 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5100 public static extern bool SetKeyboardState(byte[] lpKeyState);
5101
5102 public static void SetLang(int handle, string lang)
5103 {
5104 int num = NativeMethods.LoadKeyboardLayout(lang, 1);
5105 NativeMethods.PostMessage((IntPtr)handle, (IntPtr)80, (IntPtr)1, (IntPtr)num);
5106 }
5107
5108 public static void SimulateKeyDown(int handle, VirtualKeyCode keyCode)
5109 {
5110 INPUT nPUT = new INPUT()
5111 {
5112 Type = 1
5113 };
5114 nPUT.Data.Keyboard = new KEYBDINPUT()
5115 {
5116 KeyCode = (ushort)keyCode,
5117 Scan = 0,
5118 Flags = 0,
5119 Time = 0,
5120 ExtraInfo = IntPtr.Zero
5121 };
5122 INPUT[] nPUTArray = new INPUT[] { nPUT };
5123 if (NativeMethods.SendInput(1, nPUTArray, Marshal.SizeOf(typeof(INPUT))) == 0)
5124 {
5125 throw new Exception(string.Format("The key down simulation for {0} was not successful.", keyCode));
5126 }
5127 }
5128
5129 public static void SimulateKeyPress(VirtualKeyCode keyCode)
5130 {
5131 INPUT nPUT = new INPUT()
5132 {
5133 Type = 1
5134 };
5135 nPUT.Data.Keyboard = new KEYBDINPUT()
5136 {
5137 KeyCode = (ushort)keyCode,
5138 Scan = 0,
5139 Flags = 0,
5140 Time = 0,
5141 ExtraInfo = IntPtr.Zero
5142 };
5143 INPUT nPUT1 = new INPUT()
5144 {
5145 Type = 1
5146 };
5147 nPUT1.Data.Keyboard = new KEYBDINPUT()
5148 {
5149 KeyCode = (ushort)keyCode,
5150 Scan = 0,
5151 Flags = 2,
5152 Time = 0,
5153 ExtraInfo = IntPtr.Zero
5154 };
5155 INPUT[] nPUTArray = new INPUT[] { nPUT, nPUT1 };
5156 if (NativeMethods.SendInput(2, nPUTArray, Marshal.SizeOf(typeof(INPUT))) == 0)
5157 {
5158 throw new Exception(string.Format("The key press simulation for {0} was not successful.", keyCode));
5159 }
5160 }
5161
5162 public static void SimulateKeyUp(int handle, VirtualKeyCode keyCode)
5163 {
5164 INPUT nPUT = new INPUT()
5165 {
5166 Type = 1
5167 };
5168 nPUT.Data.Keyboard = new KEYBDINPUT()
5169 {
5170 KeyCode = (ushort)keyCode,
5171 Scan = 0,
5172 Flags = 2,
5173 Time = 0,
5174 ExtraInfo = IntPtr.Zero
5175 };
5176 INPUT[] nPUTArray = new INPUT[] { nPUT };
5177 if (NativeMethods.SendInput(1, nPUTArray, Marshal.SizeOf(typeof(INPUT))) == 0)
5178 {
5179 throw new Exception(string.Format("The key up simulation for {0} was not successful.", keyCode));
5180 }
5181 }
5182
5183 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5184 public static extern short VkKeyScan(char ch);
5185
5186 [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
5187 public static extern IntPtr WindowFromPoint(Point p);
5188
5189 public static class Langs
5190 {
5191 public const string DE = "00000407";
5192
5193 public const string US = "00000409";
5194
5195 public const string FR = "0000040C";
5196
5197 public const string RU = "00000419";
5198
5199 public const string UA = "00000422";
5200 }
5201
5202 public struct RECT
5203 {
5204 public readonly int Left;
5205
5206 public readonly int Top;
5207
5208 private readonly int Right;
5209
5210 private readonly int Bottom;
5211 }
5212 }
5213
5214 public enum VirtualKeyCode
5215 {
5216 LBUTTON = 1,
5217 RBUTTON = 2,
5218 CANCEL = 3,
5219 MBUTTON = 4,
5220 XBUTTON1 = 5,
5221 XBUTTON2 = 6,
5222 BACK = 8,
5223 TAB = 9,
5224 CLEAR = 12,
5225 RETURN = 13,
5226 SHIFT = 16,
5227 CONTROL = 17,
5228 MENU = 18,
5229 PAUSE = 19,
5230 CAPITAL = 20,
5231 HANGEUL = 21,
5232 HANGUL = 21,
5233 KANA = 21,
5234 JUNJA = 23,
5235 FINAL = 24,
5236 HANJA = 25,
5237 KANJI = 25,
5238 ESCAPE = 27,
5239 CONVERT = 28,
5240 NONCONVERT = 29,
5241 ACCEPT = 30,
5242 MODECHANGE = 31,
5243 SPACE = 32,
5244 PRIOR = 33,
5245 NEXT = 34,
5246 END = 35,
5247 HOME = 36,
5248 LEFT = 37,
5249 UP = 38,
5250 RIGHT = 39,
5251 DOWN = 40,
5252 SELECT = 41,
5253 PRINT = 42,
5254 EXECUTE = 43,
5255 SNAPSHOT = 44,
5256 INSERT = 45,
5257 DELETE = 46,
5258 HELP = 47,
5259 VK_0 = 48,
5260 VK_1 = 49,
5261 VK_2 = 50,
5262 VK_3 = 51,
5263 VK_4 = 52,
5264 VK_5 = 53,
5265 VK_6 = 54,
5266 VK_7 = 55,
5267 VK_8 = 56,
5268 VK_9 = 57,
5269 VK_A = 65,
5270 VK_B = 66,
5271 VK_C = 67,
5272 VK_D = 68,
5273 VK_E = 69,
5274 VK_F = 70,
5275 VK_G = 71,
5276 VK_H = 72,
5277 VK_I = 73,
5278 VK_J = 74,
5279 VK_K = 75,
5280 VK_L = 76,
5281 VK_M = 77,
5282 VK_N = 78,
5283 VK_O = 79,
5284 VK_P = 80,
5285 VK_Q = 81,
5286 VK_R = 82,
5287 VK_S = 83,
5288 VK_T = 84,
5289 VK_U = 85,
5290 VK_V = 86,
5291 VK_W = 87,
5292 VK_X = 88,
5293 VK_Y = 89,
5294 VK_Z = 90,
5295 LWIN = 91,
5296 RWIN = 92,
5297 APPS = 93,
5298 SLEEP = 95,
5299 NUMPAD0 = 96,
5300 NUMPAD1 = 97,
5301 NUMPAD2 = 98,
5302 NUMPAD3 = 99,
5303 NUMPAD4 = 100,
5304 NUMPAD5 = 101,
5305 NUMPAD6 = 102,
5306 NUMPAD7 = 103,
5307 NUMPAD8 = 104,
5308 NUMPAD9 = 105,
5309 MULTIPLY = 106,
5310 ADD = 107,
5311 SEPARATOR = 108,
5312 SUBTRACT = 109,
5313 DECIMAL = 110,
5314 DIVIDE = 111,
5315 F1 = 112,
5316 F2 = 113,
5317 F3 = 114,
5318 F4 = 115,
5319 F5 = 116,
5320 F6 = 117,
5321 F7 = 118,
5322 F8 = 119,
5323 F9 = 120,
5324 F10 = 121,
5325 F11 = 122,
5326 F12 = 123,
5327 F13 = 124,
5328 F14 = 125,
5329 F15 = 126,
5330 F16 = 127,
5331 F17 = 128,
5332 F18 = 129,
5333 F19 = 130,
5334 F20 = 131,
5335 F21 = 132,
5336 F22 = 133,
5337 F23 = 134,
5338 F24 = 135,
5339 NUMLOCK = 144,
5340 SCROLL = 145,
5341 LSHIFT = 160,
5342 RSHIFT = 161,
5343 LCONTROL = 162,
5344 RCONTROL = 163,
5345 LMENU = 164,
5346 RMENU = 165,
5347 BROWSER_BACK = 166,
5348 BROWSER_FORWARD = 167,
5349 BROWSER_REFRESH = 168,
5350 BROWSER_STOP = 169,
5351 BROWSER_SEARCH = 170,
5352 BROWSER_FAVORITES = 171,
5353 BROWSER_HOME = 172,
5354 VOLUME_MUTE = 173,
5355 VOLUME_DOWN = 174,
5356 VOLUME_UP = 175,
5357 MEDIA_NEXT_TRACK = 176,
5358 MEDIA_PREV_TRACK = 177,
5359 MEDIA_STOP = 178,
5360 MEDIA_PLAY_PAUSE = 179,
5361 LAUNCH_MAIL = 180,
5362 LAUNCH_MEDIA_SELECT = 181,
5363 LAUNCH_APP1 = 182,
5364 LAUNCH_APP2 = 183,
5365 OEM_1 = 186,
5366 OEM_PLUS = 187,
5367 OEM_COMMA = 188,
5368 OEM_MINUS = 189,
5369 OEM_PERIOD = 190,
5370 OEM_2 = 191,
5371 OEM_3 = 192,
5372 OEM_4 = 219,
5373 OEM_5 = 220,
5374 OEM_6 = 221,
5375 OEM_7 = 222,
5376 OEM_8 = 223,
5377 OEM_102 = 226,
5378 PROCESSKEY = 229,
5379 PACKET = 231,
5380 ATTN = 246,
5381 CRSEL = 247,
5382 EXSEL = 248,
5383 EREOF = 249,
5384 PLAY = 250,
5385 ZOOM = 251,
5386 NONAME = 252,
5387 PA1 = 253,
5388 OEM_CLEAR = 254
5389 }
5390
5391 public enum XButton : uint
5392 {
5393 XButton1 = 1,
5394 XButton2 = 2
5395 }
5396
5397}
5398
5399//СКОПИРУЙТЕ В СВОЙ ПРОЕКТ КОД ОТ ЭТОЙ СТРОКИ И НИЖЕ...
5400namespace Unicorn{
5401 //версия проекта - 1.0.9
5402 public static class AirProxyCommon{
5403 public static object Locker = new Object();
5404 public static Random RandomGenerator = new Random();
5405 }
5406
5407 public class AirProxyClient{
5408 /// <summary>
5409 /// Путь к папке с основным проектом (локальный или сетевой)
5410 /// </summary>
5411 public string MainProjectFolderPath="";
5412 /// <summary>
5413 /// Имя вашего проекта (или общее произвольное имя для нескольких проектов)
5414 /// </summary>
5415 public string ProjectNote="";
5416 /// <summary>
5417 /// Таймаут статуса "занято" прокси-сессии в секундах (в случае если получаем прокси)
5418 /// </summary>
5419 public int BusyInterval;
5420 /// <summary>
5421 /// Максимальное количество прокси-сессий текущего проекта на один AirProxy
5422 /// </summary>
5423 public int MaxSimultaneousSessions;
5424 /// <summary>
5425 /// Интервал (в минутах), в течение которого основной шаблон не будет выдавать ранее использовавшийся внешний IP проекту
5426 /// </summary>
5427 public int PreventRepeatIPInterval;
5428
5429 /// <summary>
5430 /// Результат выполнения команды. Например для take_http_proxy это будет строка прокси, которую можно далее использовать
5431 /// </summary>
5432 public string Result="";
5433
5434 /// <summary>
5435 /// Успешность выполнения командой. "ok" если команда выполнена, "error" если произошла ошибка
5436 /// </summary>
5437 public string ResultDescription="";
5438
5439 /// <summary>
5440 /// Подробное сообщение (сообщение лога) от основного шаблона по результату выполнения команды
5441 /// </summary>
5442 public string ResultMessage="";
5443
5444 /// <summary>
5445 /// Строка поиска прокси (для команды change_one_ip), или Id прокси-сессии (для команды release_proxy)
5446 /// </summary>
5447 public string SearchValue="";
5448
5449 private string JobFileName;
5450 private string Status = "";
5451
5452 /// <summary>
5453 /// Объект для работы с Unicorn AirProxy
5454 /// </summary>
5455 /// <param name="note">Имя вашего проекта (или общее произвольное имя для нескольких проектов)</param>
5456 /// <param name="maxSessions">Максимальное количество прокси-сессий текущего проекта на один AirProxy</param>
5457 /// <param name="repeatIPInterval">Интервал (в минутах), в течение которого основной шаблон не будет выдавать ранее использовавшийся внешний IP проекту</param>
5458 /// <param name="proxyBusyInterval">Таймаут статуса "занято" прокси-сессии в секундах (в случае если получаем прокси)</param>
5459 /// <param name="mainProjectFolder">Путь к папке с основным проектом (локальный или сетевой)</param>
5460 public AirProxyClient(string note, int maxSessions, int repeatIPInterval, int proxyBusyInterval, string mainProjectFolder){
5461
5462 MainProjectFolderPath = mainProjectFolder;
5463 if (MainProjectFolderPath.EndsWith(".xmlz")) MainProjectFolderPath = new FileInfo(MainProjectFolderPath).DirectoryName;
5464
5465 ProjectNote = note;
5466
5467 BusyInterval = proxyBusyInterval;
5468 MaxSimultaneousSessions = maxSessions;
5469 PreventRepeatIPInterval = repeatIPInterval;
5470
5471 }
5472
5473 private void Savecommand(string command, int timeout){
5474
5475 string strcommandData = String.Format("{0};{1};{2};{3};{4};{5};{6};{7}",
5476 DateTime.Now.ToString("dd.MM.yy HH:mm:ss"), command, timeout, ProjectNote.Replace(";", String.Empty),
5477 MaxSimultaneousSessions, PreventRepeatIPInterval, BusyInterval, SearchValue);
5478
5479 int maxTries = 3;
5480
5481 if (MainProjectFolderPath.StartsWith("http://")) {
5482
5483 for (int i=0; i<maxTries+1; i++){
5484 try{
5485 string url = MainProjectFolderPath + Convert.ToString(MainProjectFolderPath.EndsWith("/")?"":"/") + "addjob";
5486 string content = String.Format("filename={0}&data={1}",
5487 ZennoLab.Macros.TextProcessing.UrlEncode(JobFileName),
5488 ZennoLab.Macros.TextProcessing.UrlEncode(strcommandData)
5489 );
5490
5491 //File.AppendAllText(@"d:\test.txt", url + Environment.NewLine);
5492 //File.AppendAllText(@"d:\test.txt", content + Environment.NewLine);
5493
5494 string response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.POST,
5495 url, content, "application/x-www-form-urlencoded", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody,
5496 throwExceptionOnError: true);
5497
5498 if (response.Contains("204")) break;
5499 }catch(Exception e){
5500 System.Threading.Thread.Sleep(AirProxyCommon.RandomGenerator.Next(2000, 5000));
5501 JobFileName = String.Format("{0}-{1}.txt", DateTime.Now.ToString("ddMMyy-HHmmss"), AirProxyCommon.RandomGenerator.Next(111111, 999999));
5502 }
5503 if (i==maxTries) throw new Exception(String.Format("Не удалось сохранить файл задания в папке основного проекта за {0} попыток", maxTries));
5504 }
5505
5506 }else{
5507
5508 string infoFolderPath = Path.Combine(MainProjectFolderPath, @"jobs\in\");
5509 DirectoryInfo inboxFolder = new DirectoryInfo(infoFolderPath);
5510
5511 for (int i=0; i<maxTries+1; i++){
5512 try{
5513 File.WriteAllText(Path.Combine(inboxFolder.FullName, JobFileName), strcommandData);
5514 break;
5515 }catch(Exception e){
5516 System.Threading.Thread.Sleep(AirProxyCommon.RandomGenerator.Next(2000, 5000));
5517 JobFileName = String.Format("{0}-{1}.txt", DateTime.Now.ToString("ddMMyy-HHmmss"), AirProxyCommon.RandomGenerator.Next(111111, 999999));
5518 }
5519 if (i==maxTries) throw new Exception(String.Format("Не удалось сохранить файл задания в папке основного проекта за {0} попыток", maxTries));
5520 }
5521
5522 }
5523 }
5524
5525 private void ReadResult(){
5526
5527 List<string> resultDataLines = new List<string>();
5528
5529 if (MainProjectFolderPath.StartsWith("http://")) {
5530
5531 string url = String.Format(@"{0}jobs/out/{1}",
5532 MainProjectFolderPath + Convert.ToString(MainProjectFolderPath.EndsWith("/")?"":"/"),
5533 JobFileName);
5534
5535 try{
5536 string response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.GET,
5537 url, "", "", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly,
5538 throwExceptionOnError: true);
5539
5540 if (String.IsNullOrWhiteSpace(response)) return;
5541 resultDataLines = Regex.Split(response, @"\r\n").ToList();
5542
5543 }catch{
5544 return;
5545 }
5546
5547 }else{
5548
5549 string outFolderPath = Path.Combine(MainProjectFolderPath, @"jobs\out\");
5550 DirectoryInfo outbox = new DirectoryInfo(outFolderPath);
5551 string outFilePath = Path.Combine(outbox.FullName, JobFileName);
5552
5553 if (!File.Exists(outFilePath)) return;
5554 try{ resultDataLines = File.ReadAllLines(outFilePath).ToList(); }catch{ return; }
5555 try{File.Delete(outFilePath);}catch{}
5556
5557 }
5558
5559 if (resultDataLines.Count==0) throw new Exception("Не удалось получить результат выполнения команды. Файл пуст");
5560
5561 string resultData = resultDataLines[0];
5562 string[] arrResultData = resultData.Split(';');
5563 resultDataLines.RemoveAt(0);
5564 if (resultDataLines.Count>0) ResultMessage = String.Join(Environment.NewLine, resultDataLines);
5565
5566 int resultLength = 11;
5567 if (arrResultData.Length != resultLength) throw new Exception(String.Format("Неверная размерность массива с результатами: {0} элементов вместо {1} - {2}",
5568 arrResultData.Length, resultLength, resultData));
5569
5570 SearchValue = arrResultData[7];
5571 Status = arrResultData[8];
5572 Result = arrResultData[9];
5573 ResultDescription = arrResultData[10];
5574
5575 }
5576
5577 /// <summary>
5578 /// Передача команды основному шаблону и получение результата
5579 /// </summary>
5580 /// <param name="command">Команда. Возможные варианты: take_http_proxy, take_socks_proxy, release_proxy, get_stats, reinitialize, clear_log</param>
5581 /// <param name="timeout">Таймаут выполнения команды (в секундах)</param>
5582 public void RunCommand(string command, int timeout){
5583
5584 if (String.IsNullOrWhiteSpace(MainProjectFolderPath)) throw new Exception("Не указана папка основного проекта Unicorn AirProxy или ссылка к API");
5585
5586 if (!MainProjectFolderPath.StartsWith("http://") && !Directory.Exists(MainProjectFolderPath))
5587 throw new Exception(String.Format("Не удалось обнаружить папку основного проекта Unicorn AirProxy ({0})", MainProjectFolderPath));
5588
5589 Status="waiting";
5590
5591 lock(AirProxyCommon.Locker){
5592 JobFileName = String.Format("{0}-{1}.txt", DateTime.Now.ToString("ddMMyy-HHmmss"), AirProxyCommon.RandomGenerator.Next(111111, 999999));
5593 }
5594
5595 Savecommand(command, timeout);
5596 DateTime startDT = DateTime.Now;
5597 TimeSpan tstimeout = new TimeSpan(0, 0, 0, timeout, 0);
5598
5599 while(true){
5600 ReadResult();
5601 if (Status!="waiting") break;
5602 if (timeout>0 && DateTime.Now>=startDT+tstimeout) throw new Exception(String.Format("Не удалось выполнить команду {0} за {1} секунд", command, timeout));
5603 System.Threading.Thread.Sleep(1000);
5604 }
5605
5606 if (ResultDescription!="ok") throw new Exception(ResultMessage);
5607 }
5608 }
5609}
5610//СКОПИРУЙТЕ В СВОЙ ПРОЕКТ КОД ОТ ЭТОЙ СТРОКИ И ВЫШЕ...