You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

334 lines
9.8KB

  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. /// <summary>
  65. /// 実行対象日か判定する
  66. /// </summary>
  67. public virtual bool IsWorkDate() {
  68. return true;
  69. }
  70. protected void Click(String xpath, bool wait = true) {
  71. if (wait) {
  72. var ele = wait_.Until(ExpectedConditions.ElementToBeClickable(By.XPath(xpath)));
  73. ele.Click();
  74. } else {
  75. var ele = driver_.FindElementByXPath(xpath);
  76. ele.Click();
  77. }
  78. Console.WriteLine($"Click {xpath}");
  79. Wait(interval_milisec_);
  80. }
  81. protected void Click(IWebElement ele) {
  82. ele.Click();
  83. Wait(interval_milisec_);
  84. }
  85. protected void Send(String xpath, String value, bool enter = false) {
  86. var ele = wait_.Until(ExpectedConditions.ElementIsVisible(By.XPath(xpath)));
  87. ele.SendKeys(value);
  88. if (enter) {
  89. ele.SendKeys(OpenQA.Selenium.Keys.Enter);
  90. }
  91. Wait(interval_milisec_);
  92. }
  93. protected void Clear(String xpath) {
  94. var ele = wait_.Until(ExpectedConditions.ElementExists(By.XPath(xpath)));
  95. ele.Clear();
  96. Wait(interval_milisec_);
  97. }
  98. protected void Select(String xpath, String value) {
  99. try {
  100. var ele = wait_.Until(ExpectedConditions.ElementIsVisible(By.XPath(xpath)));
  101. var select = new SelectElement(ele);
  102. var options = select.Options;
  103. select.SelectByValue(value);
  104. Wait(interval_milisec_);
  105. } catch (Exception e) {
  106. Console.WriteLine($" Select failed xpath:{xpath} value:{value}");
  107. throw e;
  108. }
  109. }
  110. /// <summary>
  111. /// ダウンロードを開始したファイルを完了まで監視する
  112. /// 完了後はダウンロード完了ディレクトリに移動する
  113. /// </summary>
  114. /// <returns></returns>
  115. protected void WaitForDownload(String filename) {
  116. String tmpdownload_dir = DriverFactory.GetTmpDownloadDir();
  117. String download_dir = DriverFactory.GetDownloadDir();
  118. int limit_start = 0;
  119. long last_size = 0;
  120. String complete_filename = "";
  121. while (true) {
  122. var dir = new DirectoryInfo(tmpdownload_dir);
  123. var files = dir.GetFiles();
  124. if (files.Length != 0) {
  125. var file = files[0];
  126. if (file.Name.Contains(".crdownload") || file.Name.Contains(".tmp")) {
  127. // ダウンロード継続
  128. last_size = file.Length;
  129. logger_.Info($"ダウンロード監視中:{file.Name} size:{file.Length}");
  130. } else if (file.Length == last_size) {
  131. // ダウンロード完了
  132. logger_.Info($"ダウンロード完了:{file.Name} size:{file.Length}");
  133. complete_filename = file.Name;
  134. break;
  135. } else {
  136. // ダウンロード継続
  137. last_size = file.Length;
  138. logger_.Info($"ダウンロード監視中:{file.Name} size:{file.Length}");
  139. }
  140. } else {
  141. // ファイルが存在しない場合は、一定回数リトライし
  142. // 規定回数存在しない場合は失敗とする。
  143. if (10 < limit_start) {
  144. throw new Exception("ダウンロード開始失敗");
  145. }
  146. logger_.Info($"ダウンロード開始待ち");
  147. limit_start++;
  148. }
  149. Wait(500);
  150. }
  151. // ファイルの移動
  152. String source_filename = $@"{tmpdownload_dir}\{complete_filename}";
  153. String dest_filename = $@"{download_dir}\{filename}";
  154. System.IO.File.Move(source_filename, dest_filename, true);
  155. }
  156. protected void Wait(int milisec) {
  157. Thread.Sleep(milisec);
  158. }
  159. protected String GetSpotID(String parking_name) {
  160. if (!dic_.ContainsKey(parking_name)) {
  161. throw new ArgumentException();
  162. }
  163. return dic_[parking_name];
  164. }
  165. protected class CSVConfig {
  166. public bool header = false;
  167. public List<String> remove_char = new List<string>();
  168. }
  169. protected List<String[]> ReadCsv(String csvpath, CSVConfig config, Encoding enc) {
  170. var list = new List<String[]>();
  171. var fs = new FileStream(csvpath, FileMode.Open);
  172. var data = new byte[fs.Length];
  173. fs.Read(data, 0, data.Length);
  174. fs.Close();
  175. var content = enc.GetString(data);
  176. var lines = content.Split("\n");
  177. bool header_skip = config.header;
  178. foreach (var line in lines) {
  179. var tmpline = line;
  180. line.Trim();
  181. // 空の行はスキップ
  182. if (line.Length == 0) {
  183. continue;
  184. }
  185. // ヘッダー行のスキップ制御
  186. if (header_skip) {
  187. header_skip = false;
  188. continue;
  189. }
  190. // 囲み文字の削除
  191. if (config.remove_char != null) {
  192. foreach (var remove_char in config.remove_char) {
  193. tmpline = tmpline.Replace(remove_char, "");
  194. }
  195. }
  196. var values = tmpline.Split(",");
  197. var elements = new String[values.Length];
  198. int index = 0;
  199. foreach (var ele in values) {
  200. elements[index++] = ele.Trim();
  201. }
  202. list.Add(elements);
  203. }
  204. return list;
  205. }
  206. /// <summary>
  207. /// デフォルトのフレームにもどる
  208. /// </summary>
  209. protected void SwitchToFrame() {
  210. driver_.SwitchTo().DefaultContent();
  211. }
  212. /// <summary>
  213. /// フレームを切り替える。
  214. /// </summary>
  215. /// <param name="xpath"></param>
  216. protected void SwitchToFrame(String xpath) {
  217. var frame = wait_.Until(ExpectedConditions.ElementExists(By.XPath(xpath)));
  218. driver_.SwitchTo().Frame(frame);
  219. }
  220. /// <summary>
  221. /// 空の可能性があるソースをDateTimeへ変換する際、Null許容型として変換する。
  222. /// </summary>
  223. /// <param name="source"></param>
  224. /// <returns></returns>
  225. protected DateTime? GetDateTime(String source) {
  226. if (source != null && 0 < source.Length) {
  227. return DateTime.Parse(source);
  228. } else {
  229. return null;
  230. }
  231. }
  232. protected void CloseAlert() {
  233. try {
  234. var alert = wait_.Until(ExpectedConditions.AlertIsPresent());
  235. alert.Accept();
  236. } catch (Exception) {
  237. logger_.Info("アラート表示なし");
  238. return;
  239. }
  240. }
  241. }
  242. }