Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

289 lignes
8.5KB

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