1237 lines
48 KiB

  1. using CounsellorBL.BLStructure;
  2. using log4net;
  3. using log4net.Config;
  4. using Microsoft.Extensions.Configuration;
  5. using MonumentDefine;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. using OT.COM.SignalerMessage;
  9. using SeleniumBrowser;
  10. using SoldierData.EnterprizeV4;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Diagnostics;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Reflection;
  18. using System.Runtime.InteropServices;
  19. using System.Text;
  20. using System.Threading;
  21. using System.Windows.Forms;
  22. using static MonumentDefine.Enums;
  23. namespace TruckAP
  24. {
  25. public partial class Form1 : Form
  26. {
  27. const string ScriptFolder = "RunScripts2";
  28. public string g_apiServer { get; set; }
  29. string UseOrigtekrpa = "false";
  30. public List<string> g_lsGroupUidsPost { get; set; } = null;
  31. public List<string> g_lsGroupUidsRPA { get; set; } = null;
  32. private readonly static ILog _log = LogManager.GetLogger(typeof(Form1));
  33. private readonly Dictionary<string, string> _dicSetting = new Dictionary<string, string>();
  34. private int _nAdditional_Record = 0;
  35. [DllImport("User32.dll")]
  36. private static extern int SetForegroundWindow(IntPtr point);
  37. public const string FFMPEG_FILE = "ffmpeg.exe";
  38. public const string RECORD_FILE = "Record.mp4";
  39. public const string group_uids_post = "group_uids_post";
  40. public const string group_uids_rpa = "group_uids_rpa";
  41. private List<tb_grp_group2user> _lgroup2user2 { get; set; } = new List<tb_grp_group2user>();
  42. public Form1()
  43. {
  44. LoadLog4netConfig();
  45. _log.Info("Form1 Constructor start");
  46. InitializeComponent();
  47. GetConfig();
  48. _log.Info("Form1 Constructor End");
  49. }
  50. private void GetConfig()
  51. {
  52. _log.Info($"Form1 GetConfig start. Current Dir={Directory.GetCurrentDirectory()}");
  53. IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
  54. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
  55. IEnumerable<IConfigurationSection> ics = configuration.GetSection("appSettings").GetChildren();
  56. foreach (IConfigurationSection ic in ics)
  57. {
  58. _dicSetting.Add(ic.Key, ic.Value);
  59. }
  60. if (_dicSetting.ContainsKey("additional_record_time"))
  61. {
  62. int.TryParse(_dicSetting["additional_record_time"], out _nAdditional_Record);
  63. }
  64. UseOrigtekrpa = _dicSetting.ContainsKey("use_origtekrpa") ? (_dicSetting["use_origtekrpa"].ToLower() == "true" ? "true" : "false") : "false";
  65. _log.Info("Form1 GetConfig end");
  66. }
  67. internal string getArticleInRange(string i_sMethod, out QueryResponse o_qrRes)
  68. {
  69. string sMsg = null;
  70. QueryResponse qrRes = null;
  71. _log.Info($"Start getArticleInRange method={i_sMethod}");
  72. try
  73. {
  74. do
  75. {
  76. string sServerURL = g_apiServer;
  77. string sCmdURL = $"{sServerURL}/Cmd";
  78. sMsg = Query(sCmdURL, "GROUP.ArticleManage2Service", i_sMethod, out CResponseMessage crpArticleWait);
  79. if (sMsg != null)
  80. {
  81. break;
  82. }
  83. qrRes = (crpArticleWait.param["data"] as JToken).ToObject<QueryResponse>();
  84. if (qrRes == null)
  85. {
  86. sMsg = "CONVERT FAIL";
  87. break;
  88. }
  89. int nLim = qrRes.Records.Count();
  90. for (int nIdx = nLim - 1; nIdx >= 0; nIdx--)
  91. {
  92. Dictionary<string, object> f = qrRes.Records[nIdx];
  93. if (f.ContainsKey(tb_grp_article.CN_POST_STATUS) && int.TryParse(f[tb_grp_article.CN_POST_STATUS].ToString(), out int nStatus))
  94. {
  95. f[tb_grp_article.CN_POST_STATUS] = (Enums.EPostStatus)nStatus;
  96. }
  97. }
  98. }
  99. while (false);
  100. }
  101. catch (Exception ex)
  102. {
  103. sMsg = $"Process fail. ErrorMsg={ex.Message}";
  104. }
  105. if (sMsg != null)
  106. {
  107. _log.Error(sMsg);
  108. }
  109. _log.Info($"End getArticleInRange method={i_sMethod}");
  110. o_qrRes = qrRes;
  111. return sMsg;
  112. }
  113. private string prepareGroup2User()
  114. {
  115. string sMsg = null;
  116. try
  117. {
  118. do
  119. {
  120. _lgroup2user2.Clear();
  121. string sServerURL = g_apiServer;
  122. string sCmdURL = $"{sServerURL}/Cmd";
  123. Dictionary<string, object> dicPara = new Dictionary<string, object>
  124. {
  125. {
  126. BLWording.QRY_MASTER,
  127. new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
  128. { BLWording.WHEREDATA, null }
  129. } }
  130. }
  131. };
  132. sMsg = _Action(sCmdURL, "GROUP.GroupUserService", "Read", out CResponseMessage o_crpResult, dicPara);
  133. if (sMsg != null)
  134. {
  135. break;
  136. }
  137. QueryResponse qrRes = (o_crpResult.param["data"] as JToken).ToObject<QueryResponse>();
  138. qrRes.Records.ForEach(f =>
  139. {
  140. tb_grp_group2user u = new tb_grp_group2user();
  141. u.FillData(f);
  142. _lgroup2user2.Add(u);
  143. });
  144. }
  145. while (false);
  146. }
  147. catch (Exception ex)
  148. {
  149. sMsg = ex.Message;
  150. }
  151. return sMsg;
  152. }
  153. internal string Run(string sCmd)
  154. {
  155. string sMsg = null;
  156. _log.Info("Start Run With Cmd = " + sCmd);
  157. try
  158. {
  159. do
  160. {
  161. sMsg = prepareGroup2User();
  162. if (sMsg != null)
  163. {
  164. break;
  165. }
  166. switch (sCmd)
  167. {
  168. case "-a":
  169. sMsg = DoPost();
  170. break;
  171. case "-v":
  172. sMsg = DoMedia();
  173. break;
  174. case "":
  175. sMsg = DoPost();
  176. sMsg = DoMedia();
  177. break;
  178. }
  179. }
  180. while (false);
  181. }
  182. catch (Exception ex)
  183. {
  184. sMsg = ex.Message;
  185. }
  186. _log.Info("End Run");
  187. return sMsg;
  188. }
  189. private string DoPost()
  190. {
  191. string sMsg = null;
  192. try
  193. {
  194. do
  195. {
  196. _log.Info("Run DoPost");
  197. sMsg = getArticleInRange("GetScheduleWaitingArticleInRange", out QueryResponse qrRes);
  198. if (sMsg != null)
  199. {
  200. break;
  201. }
  202. if (qrRes.Records.Any())
  203. {
  204. _HandlePost(qrRes.Records);
  205. }
  206. sMsg = getArticleInRange("GetFailWaitingArticleInRange", out qrRes);
  207. if (sMsg != null)
  208. {
  209. break;
  210. }
  211. _log.Info("Run DoPost Fail Case");
  212. if (qrRes.Records.Any())
  213. {
  214. _HandleFailPost(qrRes.Records);
  215. }
  216. } while (false);
  217. }
  218. catch (Exception ex)
  219. {
  220. sMsg = ex.Message;
  221. }
  222. _log.Info("Run DoPost End");
  223. return sMsg;
  224. }
  225. private string DoMedia()
  226. {
  227. string sMsg = null;
  228. try
  229. {
  230. do
  231. {
  232. _log.Info("Run DoMedia");
  233. sMsg = getArticleInRange("GetMediadWaitingArticleInRange", out QueryResponse qrRes);
  234. if (sMsg != null)
  235. {
  236. break;
  237. }
  238. if (qrRes.Records.Any())
  239. {
  240. _HandleMedia(qrRes.Records);
  241. }
  242. sMsg = getArticleInRange("GetFailWaitingArticleInRange", out qrRes);
  243. if (sMsg != null && qrRes.Records.Any())
  244. {
  245. break;
  246. }
  247. _log.Info("Run DoMedia Fail");
  248. if (qrRes.Records.Any())
  249. {
  250. _HandleFailMedia(qrRes.Records);
  251. }
  252. } while (false);
  253. }
  254. catch (Exception ex)
  255. {
  256. sMsg = ex.Message;
  257. }
  258. _log.Info("Run DoMedia End");
  259. return sMsg;
  260. }
  261. private void _HandleFail(IEnumerable<Dictionary<string, object>> i_idic)
  262. {
  263. IEnumerable<Dictionary<string, object>> ldMedia = i_idic.Where(f => f.ContainsKey(tb_grp_article.CN_FB_ARTICLE_ID) && f[tb_grp_article.CN_FB_ARTICLE_ID] != null);
  264. _HandlePost(i_idic.Except(ldMedia));
  265. _HandleMedia(ldMedia);
  266. }
  267. private void _HandleFailPost(IEnumerable<Dictionary<string, object>> i_idic)
  268. {
  269. IEnumerable<Dictionary<string, object>> ldMedia = i_idic.Where(f => f.ContainsKey(tb_grp_article.CN_FB_ARTICLE_ID) && f[tb_grp_article.CN_FB_ARTICLE_ID] != null);
  270. _HandlePost(i_idic.Except(ldMedia));
  271. }
  272. private void _HandleFailMedia(IEnumerable<Dictionary<string, object>> i_idic)
  273. {
  274. IEnumerable<Dictionary<string, object>> ldMedia = i_idic.Where(f => f.ContainsKey(tb_grp_article.CN_FB_ARTICLE_ID) && f[tb_grp_article.CN_FB_ARTICLE_ID] != null);
  275. _HandleMedia(ldMedia);
  276. }
  277. private void _HandlePost(IEnumerable<Dictionary<string, object>> i_idic)
  278. {
  279. string sMsg = null;
  280. _log.Info("Start _HandlePost");
  281. try
  282. {
  283. do
  284. {
  285. string sServerURL = g_apiServer;
  286. string sURL = $"{sServerURL}/Cmd";
  287. string sDownloadURL = $"{sServerURL}/Task/Download/?fileid=";
  288. _log.Debug("_HandlePost f1");
  289. foreach (Dictionary<string, object> article in i_idic)
  290. {
  291. if (!article.ContainsKey(tb_grp_article.CN_GROUP_UID))
  292. {
  293. _log.Error($"{nameof(_HandlePost)} No CN_GROUP_UID");
  294. continue;
  295. }
  296. string sArticleUid = article[tb_grp_article.CN_UID].ToString();
  297. string sGroupUid = article[tb_grp_article.CN_GROUP_UID].ToString();
  298. if (!g_lsGroupUidsPost.Contains(sGroupUid))
  299. {
  300. _log.Debug($"Skip - {sArticleUid} since not matched group={sGroupUid}");
  301. continue;
  302. }
  303. _log.Debug($"_HandlePost f1.1 - {sArticleUid} ");
  304. PushPost(sURL, sDownloadURL, "GROUP.ArticleManage2Service", out CResponseMessage crpArticleWait, null, new Dictionary<string, object>() {
  305. { tb_grp_article.CN_UID, sArticleUid } });
  306. }
  307. _log.Debug("_HandlePost f2");
  308. }
  309. while (false);
  310. }
  311. catch (Exception ex)
  312. {
  313. sMsg = $"Process fail. ErrorMsg={ex.Message}";
  314. }
  315. if (sMsg != null)
  316. {
  317. _log.Error(sMsg);
  318. }
  319. }
  320. private List<string> _MediaOrder(List<string> i_lsNames, string i_sHighPriortyExt)
  321. {
  322. return i_lsNames.OrderByDescending(name =>
  323. {
  324. int nFind = name.LastIndexOf('.');
  325. if (nFind != -1)
  326. {
  327. string sExt = name.Substring(nFind + 1);
  328. nFind = i_sHighPriortyExt.IndexOf(sExt);
  329. }
  330. return nFind;
  331. }).ToList();
  332. }
  333. private string _HandleMediaAnArticle(Dictionary<string, object> dicArticle, int i_nRetry, tb_grp_group2user i_gUser)
  334. {
  335. string sMsg = null;
  336. string sServerURL = g_apiServer;
  337. string sCmdURL = $"{sServerURL}/Cmd";
  338. string sDownloadURL = $"{sServerURL}/Task/Download/?fileid=";
  339. try
  340. {
  341. do
  342. {
  343. _log.Info($"Handle article start {dicArticle[tb_grp_article.CN_NAME]}(uid={dicArticle[tb_grp_article.CN_UID]})");
  344. DateTime dtNow = DateTime.Now;
  345. string sWorkingName = $"FBUpload1920_1080_{dicArticle[tb_grp_article.CN_UID]}_{dtNow:yyyyMMddHHmmssfff}_{i_nRetry}";
  346. string sWorkingSpace = Path.Combine(Directory.GetCurrentDirectory(), $"{ScriptFolder}\\{sWorkingName}.myrpa");
  347. if (!Directory.Exists(sWorkingSpace))
  348. {
  349. Directory.CreateDirectory(sWorkingSpace);
  350. }
  351. #region
  352. sMsg = Read(sCmdURL, "GROUP.ArticleMediaService", out CResponseMessage crpArticleMedia,
  353. new Dictionary<string, object>() { { tb_grp_article_media.CN_STATUS_FLAG, 1 }, { tb_grp_article_media.CN_ARTICLE_UID, dicArticle[tb_grp_article.CN_UID] } });
  354. if (sMsg != null)
  355. {
  356. break;
  357. }
  358. List<tb_grp_article_media> qrsArticleMedia = (crpArticleMedia.param["data"] as JToken).ToObject<List<tb_grp_article_media>>();
  359. List<string> lsName = new List<string>();
  360. int nMediaCount = 0;
  361. // Dowload media
  362. for (int nMediaIdx = 0; nMediaIdx < qrsArticleMedia.Count; nMediaIdx++)
  363. {
  364. tb_grp_article_media dicMedia = qrsArticleMedia[nMediaIdx];
  365. string sMediaUid = dicMedia.media_id.ToString();
  366. string sMediaURL = $"{sDownloadURL}{sMediaUid}";
  367. _log.Info($"Downlaod media({sMediaURL}) for name={dicArticle[tb_grp_article.CN_NAME]} uid={dicArticle[tb_grp_article.CN_UID]}");
  368. using WebClient wc = new WebClient();
  369. Byte[] byData = wc.DownloadData(sMediaURL);
  370. string header = wc.ResponseHeaders["Content-Disposition"] ?? string.Empty;
  371. if (header != string.Empty)
  372. {
  373. nMediaCount++;
  374. int nExtensionIdx = header.LastIndexOf(".", StringComparison.OrdinalIgnoreCase);
  375. string sFileName = $"{nMediaCount}{header.Substring(nExtensionIdx)}";
  376. string sPath = Path.Combine(sWorkingSpace, sFileName);
  377. if (File.Exists(sPath))
  378. {
  379. File.Delete(sPath);
  380. }
  381. File.WriteAllBytes(sPath, byData);
  382. lsName.Add(sFileName);
  383. }
  384. else
  385. {
  386. sMsg = $"No Header[\"Content - Disposition\"";
  387. break;
  388. }
  389. }
  390. if (sMsg != null)
  391. {
  392. break;
  393. }
  394. if (lsName.Count == 0)
  395. {
  396. break;
  397. }
  398. #endregion
  399. string sFBID = dicArticle[tb_grp_article.CN_FB_ARTICLE_ID].ToString();
  400. string[] saFBID = sFBID.Split("_".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  401. _log.Info($"Generate Script for name={dicArticle[tb_grp_article.CN_NAME]} uid={dicArticle[tb_grp_article.CN_UID]} ");
  402. if (UseOrigtekrpa == "true")
  403. {
  404. sMsg = generateOrigtekRPAScrit(sWorkingName,
  405. sWorkingSpace,
  406. i_gUser.fb_account,
  407. i_gUser.fb_password,
  408. saFBID[0],
  409. saFBID[1],
  410. lsName);
  411. if (sMsg != null)
  412. {
  413. break;
  414. }
  415. sMsg = RunOrigtekRPAScript(sWorkingSpace);
  416. if (sMsg != null)
  417. {
  418. break;
  419. }
  420. _log.Info($"RunScript result = '{sMsg}'");
  421. }
  422. else
  423. {
  424. sMsg = generatePupetterScrit(sWorkingName,
  425. sWorkingSpace,
  426. i_gUser.fb_account,
  427. i_gUser.fb_password,
  428. saFBID[0],
  429. saFBID[1],
  430. lsName);
  431. sMsg = RunPupetterScript(sWorkingSpace);
  432. _log.Info($"generatePupetterScrit result = '{sMsg}'");
  433. }
  434. #region Origtek RPA
  435. #endregion
  436. _log.Info($"Handle article end {dicArticle[tb_grp_article.CN_NAME]}(uid={dicArticle[tb_grp_article.CN_UID]})");
  437. }
  438. while (false);
  439. }
  440. catch (Exception ex)
  441. {
  442. sMsg = ex.Message;
  443. _log.Error($"Process name:(uid={dicArticle[tb_grp_article.CN_UID]}) exception fail. ErrorMsg={ex.Message} ");
  444. }
  445. return sMsg;
  446. }
  447. public string RunPupetterScript(string i_sWorkingSpace)
  448. {
  449. string sMsg = null;
  450. try
  451. {
  452. do
  453. {
  454. _log.Info($"RunPupetterScript('{i_sWorkingSpace}')");
  455. var proc = new System.Diagnostics.Process();
  456. proc.StartInfo.CreateNoWindow = true;
  457. proc.StartInfo.RedirectStandardInput = true;
  458. proc.StartInfo.RedirectStandardOutput = true;
  459. proc.StartInfo.UseShellExecute = false;
  460. proc.StartInfo.RedirectStandardError = true;
  461. proc.StartInfo.FileName = "node.exe";
  462. proc.StartInfo.Arguments = $"\"{Path.Combine(i_sWorkingSpace, "pupetter.js")}\"";
  463. proc.Start();
  464. string sOut = proc.StandardOutput.ReadToEnd();
  465. proc.WaitForExit();
  466. if (!string.IsNullOrWhiteSpace(sOut))
  467. {
  468. _log.Debug($"RPA Console output: {sOut}");
  469. if (sOut.Trim() != "OK")
  470. {
  471. sMsg = sOut;
  472. }
  473. }
  474. _log.Info($"pupetter result '{sOut}'");
  475. }
  476. while (false);
  477. }
  478. catch (Exception ex)
  479. {
  480. sMsg = ex.Message;
  481. }
  482. return sMsg;
  483. }
  484. public string RunOrigtekRPAScript(string i_sWorkingSpace)
  485. {
  486. string sMsg = null;
  487. try
  488. {
  489. do
  490. {
  491. FileInfo fi = new FileInfo(_dicSetting["rpa"]);
  492. _log.Debug($"RPA={_dicSetting["rpa"]}");
  493. using Process pRun = new Process();
  494. pRun.StartInfo.FileName = _dicSetting["rpa"];
  495. pRun.StartInfo.Arguments = $"-w \"{i_sWorkingSpace}\"";
  496. pRun.StartInfo.UseShellExecute = false;
  497. pRun.StartInfo.RedirectStandardOutput = true;
  498. pRun.StartInfo.WorkingDirectory = fi.Directory.FullName;
  499. pRun.Start();
  500. pRun.WaitForExit(150000);
  501. string sOut = pRun.StandardOutput.ReadToEnd();
  502. if (!string.IsNullOrWhiteSpace(sOut))
  503. {
  504. sMsg = sOut;
  505. break;
  506. }
  507. }
  508. while (false);
  509. }
  510. catch (Exception ex)
  511. {
  512. sMsg = ex.Message;
  513. }
  514. return sMsg;
  515. }
  516. private void _HandleMedia(IEnumerable<Dictionary<string, object>> i_idicArticles)
  517. {
  518. try
  519. {
  520. do
  521. {
  522. string sServerURL = g_apiServer;
  523. string sCmdURL = $"{sServerURL}/Cmd";
  524. int nLocalRetryMax = _dicSetting.ContainsKey("localretry") ? Int32.Parse(_dicSetting["localretry"]) : 1;
  525. _log.Info($"nLocalRetryMax = {nLocalRetryMax}");
  526. // 跑每篇文章
  527. foreach (Dictionary<string, object> dicArticle in i_idicArticles)
  528. {
  529. if (!dicArticle.ContainsKey(tb_grp_article.CN_GROUP_UID))
  530. {
  531. _log.Error($"{nameof(_HandleMedia)} No CN_GROUP_UID");
  532. continue;
  533. }
  534. string sArticleUid = dicArticle[tb_grp_article.CN_UID].ToString();
  535. string sGroupUid = dicArticle[tb_grp_article.CN_GROUP_UID].ToString();
  536. if (!g_lsGroupUidsRPA.Contains(sGroupUid))
  537. {
  538. _log.Debug($"Skip - {sArticleUid} since no matched group {sGroupUid}");
  539. continue;
  540. }
  541. string sMsgOneArticle = null;
  542. if (!dicArticle.ContainsKey(tb_grp_article.CN_GROUP_USER_UID))
  543. {
  544. _log.Error($"{nameof(_HandleMedia)} No CN_GROUP_USER_UID");
  545. continue;
  546. }
  547. object oUserUID = dicArticle[tb_grp_article.CN_GROUP_USER_UID];
  548. if (oUserUID == null)
  549. {
  550. _log.Error($"{nameof(_HandleMedia)} CN_GROUP_USER_UID = null");
  551. continue;
  552. }
  553. string sUserUID = oUserUID.ToString();
  554. if (string.IsNullOrWhiteSpace(sUserUID))
  555. {
  556. _log.Error($"{nameof(_HandleMedia)} IsNullOrWhiteSpace");
  557. continue;
  558. }
  559. tb_grp_group2user gUser = _lgroup2user2.FirstOrDefault(f => f.uid == sUserUID);
  560. if (gUser == null)
  561. {
  562. _log.Error($"{nameof(_HandleMedia)} No poster information");
  563. continue;
  564. }
  565. if (string.IsNullOrWhiteSpace(gUser.fb_password) || string.IsNullOrWhiteSpace(gUser.fb_account))
  566. {
  567. _log.Error($"{nameof(_HandleMedia)} No poster information {JsonConvert.SerializeObject(gUser)}");
  568. continue;
  569. }
  570. for (int nLocalRetry = 0; nLocalRetry < nLocalRetryMax; nLocalRetry++)
  571. {
  572. sMsgOneArticle = _HandleMediaAnArticle(dicArticle, nLocalRetry, gUser);
  573. if (sMsgOneArticle == null)
  574. {
  575. break;
  576. }
  577. }
  578. if (sMsgOneArticle == null)
  579. {
  580. UpdateStatus(sCmdURL, "GROUP.ArticleManage2Service", out CResponseMessage crpArticleWait,
  581. new Dictionary<string, object>() {
  582. { tb_grp_article.CN_RPA_STATUS, 1 }
  583. },
  584. new Dictionary<string, object>() { { tb_grp_article.CN_UID, dicArticle[tb_grp_article.CN_UID] } });
  585. }
  586. else
  587. {
  588. _log.Error($"Process name:{dicArticle[tb_grp_article.CN_NAME]}(uid={dicArticle[tb_grp_article.CN_UID]}) fail. ErrorMsg={sMsgOneArticle} ");
  589. UpdateStatus(sCmdURL, "GROUP.ArticleManage2Service", out CResponseMessage crpArticleWait,
  590. new Dictionary<string, object>() {
  591. { tb_grp_article.CN_RETRY, (int.Parse(dicArticle[tb_grp_article.CN_RETRY].ToString())+1) } },
  592. new Dictionary<string, object>() { { tb_grp_article.CN_UID, dicArticle[tb_grp_article.CN_UID] } });
  593. }
  594. _forceCloseAllFFMPEG();
  595. _forceCloseAllChrome();
  596. }
  597. }
  598. while (false);
  599. }
  600. catch (Exception ex)
  601. {
  602. _log.Error($"{nameof(_HandleMedia)} exception fail. ErrorMsg={ex.Message}");
  603. }
  604. if (i_idicArticles.Any())
  605. {
  606. _forceCloseAllChrome();
  607. _forceCloseAllFFMPEG();
  608. }
  609. }
  610. private void _forceCloseAllChrome()
  611. {
  612. // Force remove all chrome
  613. foreach (var process in Process.GetProcesses().Where(pr => pr.ProcessName == "chrome"))
  614. {
  615. process.Kill();
  616. }
  617. }
  618. private void _forceCloseAllFFMPEG()
  619. {
  620. // Force remove all chrome
  621. foreach (var process in Process.GetProcesses().Where(pr => pr.ProcessName == "FFMPEG_FILE"))
  622. {
  623. process.Kill();
  624. }
  625. }
  626. private string PushPost(string i_sURL, string i_sDownloadURL, string i_sModule, out CResponseMessage o_crpResult,
  627. Dictionary<string, object> i_dicData, Dictionary<string, object> i_dicWhere)
  628. {
  629. _log.Info("PushPost");
  630. Dictionary<string, object> dicPara = new Dictionary<string, object>();
  631. dicPara.Add(BLWording.QRY_MASTER, new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
  632. { BLWording.DATA, i_dicData },
  633. { BLWording.WHEREDATA, i_dicWhere },
  634. { "downloadurl", i_sDownloadURL },
  635. } });
  636. dicPara.Add("downloadurl", i_sDownloadURL);
  637. return _Action(i_sURL, i_sModule, "PushPost", out o_crpResult, dicPara);
  638. }
  639. protected string generatePupetterScrit(
  640. string i_sWorkingName,
  641. string i_sWorkSpath,
  642. string i_sAccount, string i_sPassword,
  643. string i_sGroupID, string i_sFBArticleID, List<string> i_lsMediaPath)
  644. {
  645. string sMsg = null;
  646. try
  647. {
  648. do
  649. {
  650. string sTemplate = File.ReadAllText("pupetterTemplate.jst", Encoding.UTF8);
  651. if (!Directory.Exists(i_sWorkSpath))
  652. {
  653. Directory.CreateDirectory(i_sWorkSpath);
  654. }
  655. string bNeedLogin = _dicSetting.ContainsKey("use_incognito") ? (_dicSetting["use_incognito"].ToLower() == "true" ? "true" : "false") : "false";
  656. List<string> lsMediaPath = new List<string>();
  657. if (i_lsMediaPath != null && i_lsMediaPath.Any())
  658. {
  659. i_lsMediaPath.ForEach(f =>
  660. {
  661. if (f.IndexOf(":") != -1)
  662. {
  663. lsMediaPath.Add(f);
  664. }
  665. else
  666. {
  667. lsMediaPath.Add(Path.Combine(i_sWorkSpath, f));
  668. }
  669. });
  670. }
  671. File.WriteAllText($"{Path.Combine(i_sWorkSpath, $"pupetter.js")}", sTemplate.
  672. Replace("<%NEED_LOGIN%>", bNeedLogin.ToString()).
  673. Replace("<%POSTURL%>", $"https://www.facebook.com/groups/{i_sGroupID}/permalink/{i_sFBArticleID}/").
  674. Replace("<%ACCOUNT%>", i_sAccount).
  675. Replace("<%ENTERCODE%>", i_sPassword).
  676. Replace("<%UPLOAD_MEDIA_JSONARRAY%>", JsonConvert.SerializeObject(lsMediaPath)), Encoding.UTF8);
  677. }
  678. while (false);
  679. }
  680. catch (Exception ex)
  681. {
  682. System.Diagnostics.Debug.Write(ex.Message);
  683. // Ignore
  684. sMsg = ex.Message;
  685. }
  686. return sMsg;
  687. }
  688. protected string generateOrigtekRPAScrit(
  689. string i_sWorkingName,
  690. string i_sWorkSpath,
  691. string i_sAccount, string i_sPassword,
  692. string i_sGroupID, string i_sFBArticleID, List<string> i_lsName)
  693. {
  694. string sMsg = null;
  695. try
  696. {
  697. do
  698. {
  699. bool bNeedLogin = _dicSetting.ContainsKey("use_incognito") ? _dicSetting["use_incognito"].ToLower() == "true" : false;
  700. string sURL = $"https://www.facebook.com/groups/{i_sGroupID}/permalink/{i_sFBArticleID}/";
  701. List<CommandInfo> lci = new List<CommandInfo>();
  702. if (bNeedLogin)
  703. {
  704. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_SETURL_INCOGNITO, Value = sURL, SleepAfterEvent = 10 });
  705. }
  706. else
  707. {
  708. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_SETURL, Value = sURL, SleepAfterEvent = 10 });
  709. }
  710. // Login
  711. if (bNeedLogin)
  712. {
  713. lci.AddRange(new List<CommandInfo>() {
  714. new CommandInfo() { Command = CommandInfo.EVENT_SENDKEY, Value = "{PGDN}", SleepAfterEvent = 2 },
  715. new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER", SleepAfterEvent = 2 },
  716. new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\txtEmail.bmp" } }, SetMainBrowserFocus = true }, // 按掉FB LOADING失敗
  717. new CommandInfo() { Command = CommandInfo.EVENT_PASTE, Value = i_sAccount, SetMainBrowserFocus = true },
  718. new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER" },
  719. new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\txtPassword.bmp" } }, SetMainBrowserFocus = true },
  720. new CommandInfo() { Command = CommandInfo.EVENT_PASTE, Value = i_sPassword, SetMainBrowserFocus = true },
  721. new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnLogin.bmp" } }, SetMainBrowserFocus = true, SleepAfterEvent = 15 }, // Login
  722. });
  723. }
  724. else
  725. {
  726. lci.AddRange(new List<CommandInfo>() {
  727. new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnRestore.bmp" }, { "ACTIONIFEXIST", "TRUE"} }, SleepAfterEvent = 3}, // 按掉Chrome還原
  728. new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnDisablenotice.bmp" }, { "ACTIONIFEXIST", "TRUE"} }, SleepAfterEvent = 3}, // 關閉訊息推播
  729. });
  730. }
  731. lci.AddRange(new List<CommandInfo>() {
  732. new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnMistake.bmp" }, { "ACTIONIFEXIST", "TRUE"} }, SleepAfterEvent = 5}, // 按掉FB LOADING失敗
  733. // Enter Edit dialog
  734. new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnPopMenu.bmp" } } , SleepAfterEvent = 2},
  735. new CommandInfo() { Command = CommandInfo.EVENT_IMAGES_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnEditArticle.bmp" }, { "PATH1", @"assets\btnEditArticle2.bmp" } }, WaitTargetMilliSecond = 1500, SleepAfterEvent = 2},
  736. new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "OUTBOUND" , SleepAfterEvent = 2 },
  737. new CommandInfo() { Command = CommandInfo.EVENT_FB_REMOVE_ALLMEDIA, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnRemoveAllMedia.bmp" }, { "PATH1", @"assets\btnRemoveAllMedia2.bmp" }, { "PATH2", @"assets\btnRemoveAllMedia3.bmp" } } , SleepAfterEvent = 2},
  738. new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER" },
  739. });
  740. int nIdx = 0;
  741. foreach (string sPath in i_lsName)
  742. {
  743. if (nIdx++ == 0)
  744. {
  745. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "CENTER" });
  746. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "OUTBOUND" });
  747. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_IMAGES_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnUploadZero.bmp" }, { "PATH4", @"assets\btnUploadNoneZero4.bmp" }, { "PATH3", @"assets\btnUploadNoneZero3.bmp" }, { "PATH2", @"assets\btnUploadNoneZero2.bmp" }, { "PATH1", @"assets\btnUploadNoneZero.bmp" } }, WaitTargetMilliSecond = 1500, SleepAfterEvent = 5 });
  748. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER", SleepAfterEvent = 2 });
  749. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_SCROLL, Value = "DOWN", Repeat = 5 });
  750. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "OUTBOUND" });
  751. lci.Add(new CommandInfo()
  752. {
  753. Command = CommandInfo.EVENT_IMAGES_CLICK,
  754. Parameters = new Dictionary<string, string>() {
  755. { "PATH", @"assets\btnUploadNew1.bmp" },
  756. { "PATH1", @"assets\btnUploadNew2.bmp" },
  757. { "PATH4", @"assets\btnUploadZero.bmp" },
  758. { "PATH5", @"assets\btnUploadNoneZero.bmp" },
  759. { "PATH6", @"assets\btnUploadNoneZero2.bmp" },
  760. { "PATH7", @"assets\btnUploadNoneZero3.bmp" },
  761. { "PATH8", @"assets\btnUploadNoneZero4.bmp" }
  762. },
  763. WaitTargetMilliSecond = 1500,
  764. SleepAfterEvent = 3
  765. });
  766. }
  767. else
  768. {
  769. lci.Add(new CommandInfo()
  770. {
  771. Command = CommandInfo.EVENT_IMAGES_CLICK,
  772. Parameters = new Dictionary<string, string>() {
  773. { "PATH", @"assets\btnUploadNew3.bmp" },
  774. { "PATH3", @"assets\btnUploadNew4.bmp" },
  775. { "PATH4", @"assets\btnUploadZero.bmp" },
  776. { "PATH5", @"assets\btnUploadNoneZero.bmp" },
  777. { "PATH6", @"assets\btnUploadNoneZero2.bmp" },
  778. { "PATH7", @"assets\btnUploadNoneZero3.bmp" },
  779. { "PATH8", @"assets\btnUploadNoneZero4.bmp" }
  780. },
  781. WaitTargetMilliSecond = 1500,
  782. SleepAfterEvent = 3
  783. });
  784. }
  785. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_SETVALUETOUPLOADDLG, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "PATH", $"{sPath}" } }, SleepAfterEvent = 2 });
  786. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_CHECKWINDOWEXIST, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "EXIST", "False" } } });
  787. }
  788. /*
  789. new CommandInfo() { Command = CommandInfo.EVENT_IMAGES_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnUploadZero.bmp" }, { "PATH1", @"assets\btnUploadNoneZero.bmp" } } , SleepAfterEvent = 2},
  790. new CommandInfo() { Command = CommandInfo.EVENT_SETVALUETOUPLOADDLG, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" } , {"PATH", @"D:\Data\test\2.jpg" }}},
  791. new CommandInfo() { Command = CommandInfo.EVENT_CHECKWINDOWEXIST, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "EXIST", "False"} }},
  792. new CommandInfo() { Command = CommandInfo.EVENT_IMAGES_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnUploadZero.bmp" }, { "PATH1", @"assets\btnUploadNoneZero.bmp" } } , SleepAfterEvent = 2},
  793. new CommandInfo() { Command = CommandInfo.EVENT_SETVALUETOUPLOADDLG, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" } , {"PATH", @"D:\Data\test\1.jpg" }}},
  794. new CommandInfo() { Command = CommandInfo.EVENT_CHECKWINDOWEXIST, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "EXIST", "False"} }},
  795. */
  796. lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnSave.bmp" } }, SetMainBrowserFocus = true, SleepAfterEvent = 10 });
  797. File.WriteAllText(Path.Combine(i_sWorkSpath, $"{i_sWorkingName}.json"), JsonConvert.SerializeObject(lci), Encoding.UTF8);
  798. string[] saOriginPaths = Directory.GetFiles("FBMedia.MyScript");
  799. string sAssetsFolder = Path.Combine(i_sWorkSpath, "assets");
  800. Directory.CreateDirectory(sAssetsFolder);
  801. foreach (string sOriginPath in saOriginPaths)
  802. {
  803. FileInfo fi = new FileInfo(sOriginPath);
  804. string sNewPath = Path.Combine(sAssetsFolder, fi.Name);
  805. File.Copy(sOriginPath, sNewPath);
  806. }
  807. }
  808. while (false);
  809. }
  810. catch (Exception ex)
  811. {
  812. System.Diagnostics.Debug.Write(ex.Message);
  813. // Ignore
  814. sMsg = ex.Message;
  815. }
  816. return sMsg;
  817. }
  818. private static string _Action(string i_sURL, string i_sModule, string i_sMethod, out CResponseMessage o_crpResult,
  819. Dictionary<string, object> i_ldicPara)
  820. {
  821. string sMsg;
  822. CResponseMessage crpResult = null;
  823. try
  824. {
  825. do
  826. {
  827. SendWebApiRequest swr = new SendWebApiRequest();
  828. CRequestMessage crm = new CRequestMessage()
  829. {
  830. module = i_sModule,
  831. method = i_sMethod,
  832. param = i_ldicPara,
  833. customparam = new Dictionary<string, object>() { { BLWording.PROGRAMID, "TruckAP" } }
  834. };
  835. CReqestPack crqp = new CReqestPack
  836. {
  837. Reqs = new List<CReqestItem>()
  838. {
  839. new CReqestItem(){ Req = crm }
  840. }
  841. };
  842. sMsg = swr.RunEncryptRequest(i_sURL, crqp, out string sResult);
  843. if (sMsg != null)
  844. {
  845. _log.Error($"Result = {sMsg}");
  846. break;
  847. }
  848. else
  849. {
  850. _log.Info($"Response = {sResult}");
  851. CResponsePack crppResult = JsonConvert.DeserializeObject<CResponsePack>(sResult);
  852. if (crppResult == null)
  853. {
  854. sMsg = "Covert CResponsePack Fail";
  855. break;
  856. }
  857. CResponseMessage crp = crppResult.Reps[0];
  858. if (crp.result == EResponseResult.RR_FALSE)
  859. {
  860. sMsg = crp.msg;
  861. break;
  862. }
  863. crpResult = crp;
  864. }
  865. }
  866. while (false);
  867. }
  868. catch (Exception ex)
  869. {
  870. sMsg = ex.Message;
  871. }
  872. o_crpResult = crpResult;
  873. return sMsg;
  874. }
  875. private void UpdateStatus(string i_sURL, string i_sModule, out CResponseMessage o_crpResult,
  876. Dictionary<string, object> i_dicData, Dictionary<string, object> i_dicWhere)
  877. {
  878. Dictionary<string, object> dicPara = new Dictionary<string, object>
  879. {
  880. {
  881. BLWording.UPD_MASTER,
  882. new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
  883. { BLWording.DATA, i_dicData },
  884. { BLWording.WHEREDATA, i_dicWhere }
  885. } }
  886. }
  887. };
  888. _Action(i_sURL, i_sModule, "UpdateStatus", out o_crpResult, dicPara);
  889. }
  890. private string Read(string i_sURL, string i_sModule, out CResponseMessage o_crpResult,
  891. Dictionary<string, object> i_dicWhere)
  892. {
  893. return Query(i_sURL, i_sModule, "Read", out o_crpResult, i_dicWhere);
  894. }
  895. private string Query(string i_sURL, string i_sModule, string i_sAction, out CResponseMessage o_crpResult,
  896. Dictionary<string, object> i_dicWhere = null)
  897. {
  898. Dictionary<string, object> dicPara = new Dictionary<string, object>
  899. {
  900. {
  901. BLWording.QRY_MASTER,
  902. new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
  903. { BLWording.WHEREDATA, i_dicWhere }
  904. } }
  905. }
  906. };
  907. return _Action(i_sURL, i_sModule, i_sAction, out o_crpResult, dicPara);
  908. }
  909. private static void LoadLog4netConfig()
  910. {
  911. var repository = LogManager.CreateRepository(
  912. Assembly.GetEntryAssembly(),
  913. typeof(log4net.Repository.Hierarchy.Hierarchy)
  914. );
  915. XmlConfigurator.Configure(repository, new FileInfo("Log4Net.config"));
  916. }
  917. private void Form1_Load(object sender, EventArgs e)
  918. {
  919. string sMsg = null;
  920. try
  921. {
  922. string[] saFolders = Directory.GetDirectories(ScriptFolder);
  923. foreach (string sFoder in saFolders)
  924. {
  925. DirectoryInfo di = new DirectoryInfo(sFoder);
  926. if (di.CreationTime.AddDays(3) < DateTime.Now)
  927. {
  928. Directory.Delete(sFoder, true);
  929. }
  930. }
  931. }
  932. catch
  933. {
  934. }
  935. int nIndex = 0;
  936. StringBuilder sb = new StringBuilder($"Form1_Load start! Current directory: {Directory.GetCurrentDirectory()}");
  937. string[] saCmd = Environment.GetCommandLineArgs();
  938. foreach (string sCmd in saCmd)
  939. {
  940. sb.AppendLine($"Para[{nIndex++}] = '{sCmd}'");
  941. }
  942. _log.Info(sb.ToString());
  943. string sForceScript = null;
  944. if (saCmd.Any())
  945. {
  946. for (int nIdx = 0; nIdx < saCmd.Count(); nIdx++)
  947. {
  948. if (saCmd[nIdx] == "-w")
  949. {
  950. sForceScript = saCmd[nIdx + 1];
  951. nIdx++;
  952. }
  953. }
  954. }
  955. try
  956. {
  957. if (sForceScript != null)
  958. {
  959. if (UseOrigtekrpa == "true")
  960. {
  961. RunOrigtekRPAScript(sForceScript);
  962. }
  963. else
  964. {
  965. RunPupetterScript(sForceScript);
  966. }
  967. }
  968. else
  969. {
  970. string sapiurlori = _dicSetting["apiserver"];
  971. string[] saapiurl = sapiurlori.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  972. _log.Info($"apiserver:{sapiurlori}");
  973. g_lsGroupUidsPost = _uidsInSetting(group_uids_post);
  974. g_lsGroupUidsRPA = _uidsInSetting(group_uids_rpa);
  975. if (g_lsGroupUidsPost.Any() || g_lsGroupUidsRPA.Any())
  976. {
  977. foreach (string sapiurl in saapiurl)
  978. {
  979. g_apiServer = sapiurl;
  980. string sSuffix = "";
  981. foreach (string sCmd in saCmd)
  982. {
  983. if (sCmd == "-a" || sCmd == "-v")
  984. {
  985. sSuffix = sCmd;
  986. break;
  987. }
  988. }
  989. sMsg = Run(sSuffix);
  990. Thread.Sleep(500);
  991. }
  992. }
  993. }
  994. }
  995. catch (Exception ex)
  996. {
  997. sMsg = ex.Message;
  998. }
  999. if (sMsg != null)
  1000. {
  1001. _log.Info($"Form1_Load end with exception. {sMsg}");
  1002. }
  1003. else
  1004. {
  1005. _log.Info($"Form1_Load end Success.");
  1006. }
  1007. this.Close();
  1008. }
  1009. private List<string> _uidsInSetting(string i_sKey)
  1010. {
  1011. List<string> lsUids = new List<string>();
  1012. string sSettingValue = _dicSetting[i_sKey];
  1013. string[] saUids = sSettingValue.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  1014. foreach (string sUid in saUids)
  1015. {
  1016. lsUids.Add(sUid);
  1017. _log.Info($"{i_sKey} - group_uid:{sUid}");
  1018. }
  1019. return lsUids;
  1020. }
  1021. }
  1022. }