Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

326 Zeilen
9.6KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using System.IO;
  6. using System.IO.Compression;
  7. using OpenQA.Selenium;
  8. using OpenQA.Selenium.Chrome;
  9. using OpenQA.Selenium.Support.UI;
  10. using CSVDownloader.Code;
  11. using CSVDownloader.Store.CreditCSVData;
  12. using CSVDownloader.Store.QRCSVData;
  13. using CSVDownloader.Store.ElectronicMoneyDataStore;
  14. using ExpectedConditions = OpenQA.Selenium.Support.UI.ExpectedConditions;
  15. namespace CSVDownloader.Web {
  16. abstract class WebController {
  17. protected log4net.ILog logger_ = log4net.LogManager.GetLogger("");
  18. protected ChromeDriver driver_;
  19. protected WebDriverWait wait_;
  20. private const int interval_milisec_ = 1000;
  21. protected CreditAgent agent_;
  22. /// <summary>
  23. /// 駐車場名とSpotIDのマッピング
  24. /// </summary>
  25. protected IDictionary<String, String> dic_;
  26. public WebController(ChromeDriver driver) {
  27. driver_ = driver;
  28. wait_ = new WebDriverWait(driver_, TimeSpan.FromSeconds(10));
  29. }
  30. public virtual void SetParkingDic(IDictionary<String, String> dic) {
  31. dic_ = dic;
  32. }
  33. public CreditAgent GetCreditAgent() {
  34. return agent_;
  35. }
  36. abstract public ResultCode Login(LoginInfo login_info);
  37. abstract public ResultCode Download(DateTime from, DateTime to);
  38. abstract public ResultCode Logout();
  39. public ResultCode Archive(String archive_filename) {
  40. logger_.Info("アーカイブ開始");
  41. var dir_name = "archive";
  42. if (!Directory.Exists(dir_name)) {
  43. Directory.CreateDirectory(dir_name);
  44. }
  45. String target = @$"{dir_name}\{archive_filename}";
  46. logger_.Info($"{target}");
  47. if (System.IO.File.Exists(target)) {
  48. logger_.Info($"上書き:{target}");
  49. System.IO.File.Delete(target);
  50. }
  51. ZipFile.CreateFromDirectory("download", target);
  52. logger_.Info("アーカイブ終了");
  53. return ResultCode.OK;
  54. }
  55. public virtual List<CreditCSVData> GetCreditCSVDataList() {
  56. return new List<CreditCSVData>();
  57. }
  58. public virtual List<QRCSVData> GetQRCSVDataList() {
  59. return new List<QRCSVData>();
  60. }
  61. public virtual List<ElectronicMoneyCSVData> GetElectronicMoneyCSVDataList() {
  62. return new List<ElectronicMoneyCSVData>();
  63. }
  64. protected void Click(String xpath, bool wait = true) {
  65. if (wait) {
  66. var ele = wait_.Until(ExpectedConditions.ElementToBeClickable(By.XPath(xpath)));
  67. ele.Click();
  68. } else {
  69. var ele = driver_.FindElementByXPath(xpath);
  70. ele.Click();
  71. }
  72. Console.WriteLine($"Click {xpath}");
  73. Wait(interval_milisec_);
  74. }
  75. protected void Click(IWebElement ele) {
  76. ele.Click();
  77. Wait(interval_milisec_);
  78. }
  79. protected void Send(String xpath, String value, bool enter = false) {
  80. var ele = wait_.Until(ExpectedConditions.ElementIsVisible(By.XPath(xpath)));
  81. ele.SendKeys(value);
  82. if (enter) {
  83. ele.SendKeys(OpenQA.Selenium.Keys.Enter);
  84. }
  85. Wait(interval_milisec_);
  86. }
  87. protected void Clear(String xpath) {
  88. var ele = wait_.Until(ExpectedConditions.ElementExists(By.XPath(xpath)));
  89. ele.Clear();
  90. Wait(interval_milisec_);
  91. }
  92. protected void Select(String xpath, String value) {
  93. try {
  94. var ele = wait_.Until(ExpectedConditions.ElementIsVisible(By.XPath(xpath)));
  95. var select = new SelectElement(ele);
  96. var options = select.Options;
  97. select.SelectByValue(value);
  98. Wait(interval_milisec_);
  99. } catch (Exception e) {
  100. Console.WriteLine($" Select failed xpath:{xpath} value:{value}");
  101. throw e;
  102. }
  103. }
  104. /// <summary>
  105. /// ダウンロードを開始したファイルを完了まで監視する
  106. /// 完了後はダウンロード完了ディレクトリに移動する
  107. /// </summary>
  108. /// <returns></returns>
  109. protected void WaitForDownload(String filename) {
  110. String tmpdownload_dir = DriverFactory.GetTmpDownloadDir();
  111. String download_dir = DriverFactory.GetDownloadDir();
  112. int limit_start = 0;
  113. long last_size = 0;
  114. String complete_filename = "";
  115. while (true) {
  116. var dir = new DirectoryInfo(tmpdownload_dir);
  117. var files = dir.GetFiles();
  118. if (files.Length != 0) {
  119. var file = files[0];
  120. if (file.Name.Contains(".crdownload") || file.Name.Contains(".tmp")) {
  121. // ダウンロード継続
  122. last_size = file.Length;
  123. logger_.Info($"ダウンロード監視中:{file.Name} size:{file.Length}");
  124. } else if (file.Length == last_size) {
  125. // ダウンロード完了
  126. logger_.Info($"ダウンロード完了:{file.Name} size:{file.Length}");
  127. complete_filename = file.Name;
  128. break;
  129. } else {
  130. // ダウンロード継続
  131. last_size = file.Length;
  132. logger_.Info($"ダウンロード監視中:{file.Name} size:{file.Length}");
  133. }
  134. } else {
  135. // ファイルが存在しない場合は、一定回数リトライし
  136. // 規定回数存在しない場合は失敗とする。
  137. if (10 < limit_start) {
  138. throw new Exception("ダウンロード開始失敗");
  139. }
  140. logger_.Info($"ダウンロード開始待ち");
  141. limit_start++;
  142. }
  143. Wait(500);
  144. }
  145. // ファイルの移動
  146. String source_filename = $@"{tmpdownload_dir}\{complete_filename}";
  147. String dest_filename = $@"{download_dir}\{filename}";
  148. System.IO.File.Move(source_filename, dest_filename, true);
  149. }
  150. protected void Wait(int milisec) {
  151. Thread.Sleep(milisec);
  152. }
  153. protected String GetSpotID(String parking_name) {
  154. if (!dic_.ContainsKey(parking_name)) {
  155. throw new ArgumentException();
  156. }
  157. return dic_[parking_name];
  158. }
  159. protected class CSVConfig {
  160. public bool header = false;
  161. public List<String> remove_char = new List<string>();
  162. }
  163. protected List<String[]> ReadCsv(String csvpath, CSVConfig config, Encoding enc) {
  164. var list = new List<String[]>();
  165. var fs = new FileStream(csvpath, FileMode.Open);
  166. var data = new byte[fs.Length];
  167. fs.Read(data, 0, data.Length);
  168. fs.Close();
  169. var content = enc.GetString(data);
  170. var lines = content.Split("\n");
  171. bool header_skip = config.header;
  172. foreach (var line in lines) {
  173. var tmpline = line;
  174. line.Trim();
  175. // 空の行はスキップ
  176. if (line.Length == 0) {
  177. continue;
  178. }
  179. // ヘッダー行のスキップ制御
  180. if (header_skip) {
  181. header_skip = false;
  182. continue;
  183. }
  184. // 囲み文字の削除
  185. if (config.remove_char != null) {
  186. foreach (var remove_char in config.remove_char) {
  187. tmpline = tmpline.Replace(remove_char, "");
  188. }
  189. }
  190. var values = tmpline.Split(",");
  191. var elements = new String[values.Length];
  192. int index = 0;
  193. foreach (var ele in values) {
  194. elements[index++] = ele.Trim();
  195. }
  196. list.Add(elements);
  197. }
  198. return list;
  199. }
  200. /// <summary>
  201. /// デフォルトのフレームにもどる
  202. /// </summary>
  203. protected void SwitchToFrame() {
  204. driver_.SwitchTo().DefaultContent();
  205. }
  206. /// <summary>
  207. /// フレームを切り替える。
  208. /// </summary>
  209. /// <param name="xpath"></param>
  210. protected void SwitchToFrame(String xpath) {
  211. var frame = wait_.Until(ExpectedConditions.ElementExists(By.XPath(xpath)));
  212. driver_.SwitchTo().Frame(frame);
  213. }
  214. /// <summary>
  215. /// 空の可能性があるソースをDateTimeへ変換する際、Null許容型として変換する。
  216. /// </summary>
  217. /// <param name="source"></param>
  218. /// <returns></returns>
  219. protected DateTime? GetDateTime(String source) {
  220. if (source != null && 0 < source.Length) {
  221. return DateTime.Parse(source);
  222. } else {
  223. return null;
  224. }
  225. }
  226. protected void CloseAlert() {
  227. try {
  228. var alert = wait_.Until(ExpectedConditions.AlertIsPresent());
  229. alert.Accept();
  230. } catch (Exception) {
  231. logger_.Info("アラート表示なし");
  232. return;
  233. }
  234. }
  235. }
  236. }