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.
 
 
 
 
 
 

1238 lines
48 KiB

using CounsellorBL.BLStructure;
using log4net;
using log4net.Config;
using Microsoft.Extensions.Configuration;
using MonumentDefine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OT.COM.SignalerMessage;
using SeleniumBrowser;
using SoldierData.EnterprizeV4;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using static MonumentDefine.Enums;
namespace TruckAP
{
public partial class Form1 : Form
{
const string ScriptFolder = "RunScripts2";
public string g_apiServer { get; set; }
string UseOrigtekrpa = "false";
public List<string> g_lsGroupUidsPost { get; set; } = null;
public List<string> g_lsGroupUidsRPA { get; set; } = null;
private readonly static ILog _log = LogManager.GetLogger(typeof(Form1));
private readonly Dictionary<string, string> _dicSetting = new Dictionary<string, string>();
private int _nAdditional_Record = 0;
[DllImport("User32.dll")]
private static extern int SetForegroundWindow(IntPtr point);
public const string FFMPEG_FILE = "ffmpeg.exe";
public const string RECORD_FILE = "Record.mp4";
public const string group_uids_post = "group_uids_post";
public const string group_uids_rpa = "group_uids_rpa";
private List<tb_grp_group2user> _lgroup2user2 { get; set; } = new List<tb_grp_group2user>();
public Form1()
{
LoadLog4netConfig();
_log.Info("Form1 Constructor start");
InitializeComponent();
GetConfig();
_log.Info("Form1 Constructor End");
}
private void GetConfig()
{
_log.Info($"Form1 GetConfig start. Current Dir={Directory.GetCurrentDirectory()}");
IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
IEnumerable<IConfigurationSection> ics = configuration.GetSection("appSettings").GetChildren();
foreach (IConfigurationSection ic in ics)
{
_dicSetting.Add(ic.Key, ic.Value);
}
if (_dicSetting.ContainsKey("additional_record_time"))
{
int.TryParse(_dicSetting["additional_record_time"], out _nAdditional_Record);
}
UseOrigtekrpa = _dicSetting.ContainsKey("use_origtekrpa") ? (_dicSetting["use_origtekrpa"].ToLower() == "true" ? "true" : "false") : "false";
_log.Info("Form1 GetConfig end");
}
internal string getArticleInRange(string i_sMethod, out QueryResponse o_qrRes)
{
string sMsg = null;
QueryResponse qrRes = null;
_log.Info($"Start getArticleInRange method={i_sMethod}");
try
{
do
{
string sServerURL = g_apiServer;
string sCmdURL = $"{sServerURL}/Cmd";
sMsg = Query(sCmdURL, "GROUP.ArticleManage2Service", i_sMethod, out CResponseMessage crpArticleWait);
if (sMsg != null)
{
break;
}
qrRes = (crpArticleWait.param["data"] as JToken).ToObject<QueryResponse>();
if (qrRes == null)
{
sMsg = "CONVERT FAIL";
break;
}
int nLim = qrRes.Records.Count();
for (int nIdx = nLim - 1; nIdx >= 0; nIdx--)
{
Dictionary<string, object> f = qrRes.Records[nIdx];
if (f.ContainsKey(tb_grp_article.CN_POST_STATUS) && int.TryParse(f[tb_grp_article.CN_POST_STATUS].ToString(), out int nStatus))
{
f[tb_grp_article.CN_POST_STATUS] = (Enums.EPostStatus)nStatus;
}
}
}
while (false);
}
catch (Exception ex)
{
sMsg = $"Process fail. ErrorMsg={ex.Message}";
}
if (sMsg != null)
{
_log.Error(sMsg);
}
_log.Info($"End getArticleInRange method={i_sMethod}");
o_qrRes = qrRes;
return sMsg;
}
private string prepareGroup2User()
{
string sMsg = null;
try
{
do
{
_lgroup2user2.Clear();
string sServerURL = g_apiServer;
string sCmdURL = $"{sServerURL}/Cmd";
Dictionary<string, object> dicPara = new Dictionary<string, object>
{
{
BLWording.QRY_MASTER,
new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
{ BLWording.WHEREDATA, null }
} }
}
};
sMsg = _Action(sCmdURL, "GROUP.GroupUserService", "Read", out CResponseMessage o_crpResult, dicPara);
if (sMsg != null)
{
break;
}
QueryResponse qrRes = (o_crpResult.param["data"] as JToken).ToObject<QueryResponse>();
qrRes.Records.ForEach(f =>
{
tb_grp_group2user u = new tb_grp_group2user();
u.FillData(f);
_lgroup2user2.Add(u);
});
}
while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
}
return sMsg;
}
internal string Run(string sCmd)
{
string sMsg = null;
_log.Info("Start Run With Cmd = " + sCmd);
try
{
do
{
sMsg = prepareGroup2User();
if (sMsg != null)
{
break;
}
switch (sCmd)
{
case "-a":
sMsg = DoPost();
break;
case "-v":
sMsg = DoMedia();
break;
case "":
sMsg = DoPost();
sMsg = DoMedia();
break;
}
}
while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
}
_log.Info("End Run");
return sMsg;
}
private string DoPost()
{
string sMsg = null;
try
{
do
{
_log.Info("Run DoPost");
sMsg = getArticleInRange("GetScheduleWaitingArticleInRange", out QueryResponse qrRes);
if (sMsg != null)
{
break;
}
if (qrRes.Records.Any())
{
_HandlePost(qrRes.Records);
}
sMsg = getArticleInRange("GetFailWaitingArticleInRange", out qrRes);
if (sMsg != null)
{
break;
}
_log.Info("Run DoPost Fail Case");
if (qrRes.Records.Any())
{
_HandleFailPost(qrRes.Records);
}
} while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
}
_log.Info("Run DoPost End");
return sMsg;
}
private string DoMedia()
{
string sMsg = null;
try
{
do
{
_log.Info("Run DoMedia");
sMsg = getArticleInRange("GetMediadWaitingArticleInRange", out QueryResponse qrRes);
if (sMsg != null)
{
break;
}
if (qrRes.Records.Any())
{
_HandleMedia(qrRes.Records);
}
sMsg = getArticleInRange("GetFailWaitingArticleInRange", out qrRes);
if (sMsg != null && qrRes.Records.Any())
{
break;
}
_log.Info("Run DoMedia Fail");
if (qrRes.Records.Any())
{
_HandleFailMedia(qrRes.Records);
}
} while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
}
_log.Info("Run DoMedia End");
return sMsg;
}
private void _HandleFail(IEnumerable<Dictionary<string, object>> i_idic)
{
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);
_HandlePost(i_idic.Except(ldMedia));
_HandleMedia(ldMedia);
}
private void _HandleFailPost(IEnumerable<Dictionary<string, object>> i_idic)
{
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);
_HandlePost(i_idic.Except(ldMedia));
}
private void _HandleFailMedia(IEnumerable<Dictionary<string, object>> i_idic)
{
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);
_HandleMedia(ldMedia);
}
private void _HandlePost(IEnumerable<Dictionary<string, object>> i_idic)
{
string sMsg = null;
_log.Info("Start _HandlePost");
try
{
do
{
string sServerURL = g_apiServer;
string sURL = $"{sServerURL}/Cmd";
string sDownloadURL = $"{sServerURL}/Task/Download/?fileid=";
_log.Debug("_HandlePost f1");
foreach (Dictionary<string, object> article in i_idic)
{
if (!article.ContainsKey(tb_grp_article.CN_GROUP_UID))
{
_log.Error($"{nameof(_HandlePost)} No CN_GROUP_UID");
continue;
}
string sArticleUid = article[tb_grp_article.CN_UID].ToString();
string sGroupUid = article[tb_grp_article.CN_GROUP_UID].ToString();
if (!g_lsGroupUidsPost.Contains(sGroupUid))
{
_log.Debug($"Skip - {sArticleUid} since not matched group={sGroupUid}");
continue;
}
_log.Debug($"_HandlePost f1.1 - {sArticleUid} ");
PushPost(sURL, sDownloadURL, "GROUP.ArticleManage2Service", out CResponseMessage crpArticleWait, null, new Dictionary<string, object>() {
{ tb_grp_article.CN_UID, sArticleUid } });
}
_log.Debug("_HandlePost f2");
}
while (false);
}
catch (Exception ex)
{
sMsg = $"Process fail. ErrorMsg={ex.Message}";
}
if (sMsg != null)
{
_log.Error(sMsg);
}
}
private List<string> _MediaOrder(List<string> i_lsNames, string i_sHighPriortyExt)
{
return i_lsNames.OrderByDescending(name =>
{
int nFind = name.LastIndexOf('.');
if (nFind != -1)
{
string sExt = name.Substring(nFind + 1);
nFind = i_sHighPriortyExt.IndexOf(sExt);
}
return nFind;
}).ToList();
}
private string _HandleMediaAnArticle(Dictionary<string, object> dicArticle, int i_nRetry, tb_grp_group2user i_gUser)
{
string sMsg = null;
string sServerURL = g_apiServer;
string sCmdURL = $"{sServerURL}/Cmd";
string sDownloadURL = $"{sServerURL}/Task/Download/?fileid=";
try
{
do
{
_log.Info($"Handle article start {dicArticle[tb_grp_article.CN_NAME]}(uid={dicArticle[tb_grp_article.CN_UID]})");
DateTime dtNow = DateTime.Now;
string sWorkingName = $"FBUpload1920_1080_{dicArticle[tb_grp_article.CN_UID]}_{dtNow:yyyyMMddHHmmssfff}_{i_nRetry}";
string sWorkingSpace = Path.Combine(Directory.GetCurrentDirectory(), $"{ScriptFolder}\\{sWorkingName}.myrpa");
if (!Directory.Exists(sWorkingSpace))
{
Directory.CreateDirectory(sWorkingSpace);
}
#region
sMsg = Read(sCmdURL, "GROUP.ArticleMediaService", out CResponseMessage crpArticleMedia,
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] } });
if (sMsg != null)
{
break;
}
List<tb_grp_article_media> qrsArticleMedia = (crpArticleMedia.param["data"] as JToken).ToObject<List<tb_grp_article_media>>();
List<string> lsName = new List<string>();
int nMediaCount = 0;
// Dowload media
for (int nMediaIdx = 0; nMediaIdx < qrsArticleMedia.Count; nMediaIdx++)
{
tb_grp_article_media dicMedia = qrsArticleMedia[nMediaIdx];
string sMediaUid = dicMedia.media_id.ToString();
string sMediaURL = $"{sDownloadURL}{sMediaUid}";
_log.Info($"Downlaod media({sMediaURL}) for name={dicArticle[tb_grp_article.CN_NAME]} uid={dicArticle[tb_grp_article.CN_UID]}");
using WebClient wc = new WebClient();
Byte[] byData = wc.DownloadData(sMediaURL);
string header = wc.ResponseHeaders["Content-Disposition"] ?? string.Empty;
if (header != string.Empty)
{
nMediaCount++;
int nExtensionIdx = header.LastIndexOf(".", StringComparison.OrdinalIgnoreCase);
string sFileName = $"{nMediaCount}{header.Substring(nExtensionIdx)}";
string sPath = Path.Combine(sWorkingSpace, sFileName);
if (File.Exists(sPath))
{
File.Delete(sPath);
}
File.WriteAllBytes(sPath, byData);
lsName.Add(sFileName);
}
else
{
sMsg = $"No Header[\"Content - Disposition\"";
break;
}
}
if (sMsg != null)
{
break;
}
if (lsName.Count == 0)
{
break;
}
#endregion
string sFBID = dicArticle[tb_grp_article.CN_FB_ARTICLE_ID].ToString();
string[] saFBID = sFBID.Split("_".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
_log.Info($"Generate Script for name={dicArticle[tb_grp_article.CN_NAME]} uid={dicArticle[tb_grp_article.CN_UID]} ");
if (UseOrigtekrpa == "true")
{
sMsg = generateOrigtekRPAScrit(sWorkingName,
sWorkingSpace,
i_gUser.fb_account,
i_gUser.fb_password,
saFBID[0],
saFBID[1],
lsName);
if (sMsg != null)
{
break;
}
sMsg = RunOrigtekRPAScript(sWorkingSpace);
if (sMsg != null)
{
break;
}
_log.Info($"RunScript result = '{sMsg}'");
}
else
{
sMsg = generatePupetterScrit(sWorkingName,
sWorkingSpace,
i_gUser.fb_account,
i_gUser.fb_password,
saFBID[0],
saFBID[1],
lsName);
sMsg = RunPupetterScript(sWorkingSpace);
_log.Info($"generatePupetterScrit result = '{sMsg}'");
}
#region Origtek RPA
#endregion
_log.Info($"Handle article end {dicArticle[tb_grp_article.CN_NAME]}(uid={dicArticle[tb_grp_article.CN_UID]})");
}
while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
_log.Error($"Process name:(uid={dicArticle[tb_grp_article.CN_UID]}) exception fail. ErrorMsg={ex.Message} ");
}
return sMsg;
}
public string RunPupetterScript(string i_sWorkingSpace)
{
string sMsg = null;
try
{
do
{
_log.Info($"RunPupetterScript('{i_sWorkingSpace}')");
var proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.FileName = "node.exe";
proc.StartInfo.Arguments = $"\"{Path.Combine(i_sWorkingSpace, "pupetter.js")}\"";
proc.Start();
string sOut = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
if (!string.IsNullOrWhiteSpace(sOut))
{
_log.Debug($"RPA Console output: {sOut}");
if (sOut.Trim() != "OK")
{
sMsg = sOut;
}
}
_log.Info($"pupetter result '{sOut}'");
}
while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
}
return sMsg;
}
public string RunOrigtekRPAScript(string i_sWorkingSpace)
{
string sMsg = null;
try
{
do
{
FileInfo fi = new FileInfo(_dicSetting["rpa"]);
_log.Debug($"RPA={_dicSetting["rpa"]}");
using Process pRun = new Process();
pRun.StartInfo.FileName = _dicSetting["rpa"];
pRun.StartInfo.Arguments = $"-w \"{i_sWorkingSpace}\"";
pRun.StartInfo.UseShellExecute = false;
pRun.StartInfo.RedirectStandardOutput = true;
pRun.StartInfo.WorkingDirectory = fi.Directory.FullName;
pRun.Start();
pRun.WaitForExit(150000);
string sOut = pRun.StandardOutput.ReadToEnd();
if (!string.IsNullOrWhiteSpace(sOut))
{
sMsg = sOut;
break;
}
}
while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
}
return sMsg;
}
private void _HandleMedia(IEnumerable<Dictionary<string, object>> i_idicArticles)
{
try
{
do
{
string sServerURL = g_apiServer;
string sCmdURL = $"{sServerURL}/Cmd";
int nLocalRetryMax = _dicSetting.ContainsKey("localretry") ? Int32.Parse(_dicSetting["localretry"]) : 1;
_log.Info($"nLocalRetryMax = {nLocalRetryMax}");
// 跑每篇文章
foreach (Dictionary<string, object> dicArticle in i_idicArticles)
{
if (!dicArticle.ContainsKey(tb_grp_article.CN_GROUP_UID))
{
_log.Error($"{nameof(_HandleMedia)} No CN_GROUP_UID");
continue;
}
string sArticleUid = dicArticle[tb_grp_article.CN_UID].ToString();
string sGroupUid = dicArticle[tb_grp_article.CN_GROUP_UID].ToString();
if (!g_lsGroupUidsRPA.Contains(sGroupUid))
{
_log.Debug($"Skip - {sArticleUid} since no matched group {sGroupUid}");
continue;
}
string sMsgOneArticle = null;
if (!dicArticle.ContainsKey(tb_grp_article.CN_GROUP_USER_UID))
{
_log.Error($"{nameof(_HandleMedia)} No CN_GROUP_USER_UID");
continue;
}
object oUserUID = dicArticle[tb_grp_article.CN_GROUP_USER_UID];
if (oUserUID == null)
{
_log.Error($"{nameof(_HandleMedia)} CN_GROUP_USER_UID = null");
continue;
}
string sUserUID = oUserUID.ToString();
if (string.IsNullOrWhiteSpace(sUserUID))
{
_log.Error($"{nameof(_HandleMedia)} IsNullOrWhiteSpace");
continue;
}
tb_grp_group2user gUser = _lgroup2user2.FirstOrDefault(f => f.uid == sUserUID);
if (gUser == null)
{
_log.Error($"{nameof(_HandleMedia)} No poster information");
continue;
}
if (string.IsNullOrWhiteSpace(gUser.fb_password) || string.IsNullOrWhiteSpace(gUser.fb_account))
{
_log.Error($"{nameof(_HandleMedia)} No poster information {JsonConvert.SerializeObject(gUser)}");
continue;
}
for (int nLocalRetry = 0; nLocalRetry < nLocalRetryMax; nLocalRetry++)
{
sMsgOneArticle = _HandleMediaAnArticle(dicArticle, nLocalRetry, gUser);
if (sMsgOneArticle == null)
{
break;
}
}
if (sMsgOneArticle == null)
{
UpdateStatus(sCmdURL, "GROUP.ArticleManage2Service", out CResponseMessage crpArticleWait,
new Dictionary<string, object>() {
{ tb_grp_article.CN_RPA_STATUS, 1 }
},
new Dictionary<string, object>() { { tb_grp_article.CN_UID, dicArticle[tb_grp_article.CN_UID] } });
}
else
{
_log.Error($"Process name:{dicArticle[tb_grp_article.CN_NAME]}(uid={dicArticle[tb_grp_article.CN_UID]}) fail. ErrorMsg={sMsgOneArticle} ");
UpdateStatus(sCmdURL, "GROUP.ArticleManage2Service", out CResponseMessage crpArticleWait,
new Dictionary<string, object>() {
{ tb_grp_article.CN_RETRY, (int.Parse(dicArticle[tb_grp_article.CN_RETRY].ToString())+1) } },
new Dictionary<string, object>() { { tb_grp_article.CN_UID, dicArticle[tb_grp_article.CN_UID] } });
}
_forceCloseAllFFMPEG();
_forceCloseAllChrome();
}
}
while (false);
}
catch (Exception ex)
{
_log.Error($"{nameof(_HandleMedia)} exception fail. ErrorMsg={ex.Message}");
}
if (i_idicArticles.Any())
{
_forceCloseAllChrome();
_forceCloseAllFFMPEG();
}
}
private void _forceCloseAllChrome()
{
// Force remove all chrome
foreach (var process in Process.GetProcesses().Where(pr => pr.ProcessName == "chrome"))
{
process.Kill();
}
}
private void _forceCloseAllFFMPEG()
{
// Force remove all chrome
foreach (var process in Process.GetProcesses().Where(pr => pr.ProcessName == "FFMPEG_FILE"))
{
process.Kill();
}
}
private string PushPost(string i_sURL, string i_sDownloadURL, string i_sModule, out CResponseMessage o_crpResult,
Dictionary<string, object> i_dicData, Dictionary<string, object> i_dicWhere)
{
_log.Info("PushPost");
Dictionary<string, object> dicPara = new Dictionary<string, object>();
dicPara.Add(BLWording.QRY_MASTER, new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
{ BLWording.DATA, i_dicData },
{ BLWording.WHEREDATA, i_dicWhere },
{ "downloadurl", i_sDownloadURL },
} });
dicPara.Add("downloadurl", i_sDownloadURL);
return _Action(i_sURL, i_sModule, "PushPost", out o_crpResult, dicPara);
}
protected string generatePupetterScrit(
string i_sWorkingName,
string i_sWorkSpath,
string i_sAccount, string i_sPassword,
string i_sGroupID, string i_sFBArticleID, List<string> i_lsMediaPath)
{
string sMsg = null;
try
{
do
{
string sTemplate = File.ReadAllText("pupetterTemplate.jst", Encoding.UTF8);
if (!Directory.Exists(i_sWorkSpath))
{
Directory.CreateDirectory(i_sWorkSpath);
}
string bNeedLogin = _dicSetting.ContainsKey("use_incognito") ? (_dicSetting["use_incognito"].ToLower() == "true" ? "true" : "false") : "false";
List<string> lsMediaPath = new List<string>();
if (i_lsMediaPath != null && i_lsMediaPath.Any())
{
i_lsMediaPath.ForEach(f =>
{
if (f.IndexOf(":") != -1)
{
lsMediaPath.Add(f);
}
else
{
lsMediaPath.Add(Path.Combine(i_sWorkSpath, f));
}
});
}
File.WriteAllText($"{Path.Combine(i_sWorkSpath, $"pupetter.js")}", sTemplate.
Replace("<%NEED_LOGIN%>", bNeedLogin.ToString()).
Replace("<%POSTURL%>", $"https://www.facebook.com/groups/{i_sGroupID}/permalink/{i_sFBArticleID}/").
Replace("<%ACCOUNT%>", i_sAccount).
Replace("<%ENTERCODE%>", i_sPassword).
Replace("<%UPLOAD_MEDIA_JSONARRAY%>", JsonConvert.SerializeObject(lsMediaPath)), Encoding.UTF8);
}
while (false);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message);
// Ignore
sMsg = ex.Message;
}
return sMsg;
}
protected string generateOrigtekRPAScrit(
string i_sWorkingName,
string i_sWorkSpath,
string i_sAccount, string i_sPassword,
string i_sGroupID, string i_sFBArticleID, List<string> i_lsName)
{
string sMsg = null;
try
{
do
{
bool bNeedLogin = _dicSetting.ContainsKey("use_incognito") ? _dicSetting["use_incognito"].ToLower() == "true" : false;
string sURL = $"https://www.facebook.com/groups/{i_sGroupID}/permalink/{i_sFBArticleID}/";
List<CommandInfo> lci = new List<CommandInfo>();
if (bNeedLogin)
{
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_SETURL_INCOGNITO, Value = sURL, SleepAfterEvent = 10 });
}
else
{
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_SETURL, Value = sURL, SleepAfterEvent = 10 });
}
// Login
if (bNeedLogin)
{
lci.AddRange(new List<CommandInfo>() {
new CommandInfo() { Command = CommandInfo.EVENT_SENDKEY, Value = "{PGDN}", SleepAfterEvent = 2 },
new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER", SleepAfterEvent = 2 },
new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\txtEmail.bmp" } }, SetMainBrowserFocus = true }, // 按掉FB LOADING失敗
new CommandInfo() { Command = CommandInfo.EVENT_PASTE, Value = i_sAccount, SetMainBrowserFocus = true },
new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER" },
new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\txtPassword.bmp" } }, SetMainBrowserFocus = true },
new CommandInfo() { Command = CommandInfo.EVENT_PASTE, Value = i_sPassword, SetMainBrowserFocus = true },
new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnLogin.bmp" } }, SetMainBrowserFocus = true, SleepAfterEvent = 15 }, // Login
});
}
else
{
lci.AddRange(new List<CommandInfo>() {
new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnRestore.bmp" }, { "ACTIONIFEXIST", "TRUE"} }, SleepAfterEvent = 3}, // 按掉Chrome還原
new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnDisablenotice.bmp" }, { "ACTIONIFEXIST", "TRUE"} }, SleepAfterEvent = 3}, // 關閉訊息推播
});
}
lci.AddRange(new List<CommandInfo>() {
new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnMistake.bmp" }, { "ACTIONIFEXIST", "TRUE"} }, SleepAfterEvent = 5}, // 按掉FB LOADING失敗
// Enter Edit dialog
new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnPopMenu.bmp" } } , SleepAfterEvent = 2},
new CommandInfo() { Command = CommandInfo.EVENT_IMAGES_CLICK, Parameters = new Dictionary<string, string>() { {"PATH", @"assets\btnEditArticle.bmp" }, { "PATH1", @"assets\btnEditArticle2.bmp" } }, WaitTargetMilliSecond = 1500, SleepAfterEvent = 2},
new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "OUTBOUND" , SleepAfterEvent = 2 },
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},
new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER" },
});
int nIdx = 0;
foreach (string sPath in i_lsName)
{
if (nIdx++ == 0)
{
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "CENTER" });
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "OUTBOUND" });
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 });
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_POSITION_CLICK, Value = "CENTER", SleepAfterEvent = 2 });
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_SCROLL, Value = "DOWN", Repeat = 5 });
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_MOUSE_MOVE, Value = "OUTBOUND" });
lci.Add(new CommandInfo()
{
Command = CommandInfo.EVENT_IMAGES_CLICK,
Parameters = new Dictionary<string, string>() {
{ "PATH", @"assets\btnUploadNew1.bmp" },
{ "PATH1", @"assets\btnUploadNew2.bmp" },
{ "PATH4", @"assets\btnUploadZero.bmp" },
{ "PATH5", @"assets\btnUploadNoneZero.bmp" },
{ "PATH6", @"assets\btnUploadNoneZero2.bmp" },
{ "PATH7", @"assets\btnUploadNoneZero3.bmp" },
{ "PATH8", @"assets\btnUploadNoneZero4.bmp" }
},
WaitTargetMilliSecond = 1500,
SleepAfterEvent = 3
});
}
else
{
lci.Add(new CommandInfo()
{
Command = CommandInfo.EVENT_IMAGES_CLICK,
Parameters = new Dictionary<string, string>() {
{ "PATH", @"assets\btnUploadNew3.bmp" },
{ "PATH3", @"assets\btnUploadNew4.bmp" },
{ "PATH4", @"assets\btnUploadZero.bmp" },
{ "PATH5", @"assets\btnUploadNoneZero.bmp" },
{ "PATH6", @"assets\btnUploadNoneZero2.bmp" },
{ "PATH7", @"assets\btnUploadNoneZero3.bmp" },
{ "PATH8", @"assets\btnUploadNoneZero4.bmp" }
},
WaitTargetMilliSecond = 1500,
SleepAfterEvent = 3
});
}
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_SETVALUETOUPLOADDLG, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "PATH", $"{sPath}" } }, SleepAfterEvent = 2 });
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_CHECKWINDOWEXIST, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "EXIST", "False" } } });
}
/*
new CommandInfo() { Command = CommandInfo.EVENT_IMAGES_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnUploadZero.bmp" }, { "PATH1", @"assets\btnUploadNoneZero.bmp" } } , SleepAfterEvent = 2},
new CommandInfo() { Command = CommandInfo.EVENT_SETVALUETOUPLOADDLG, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" } , {"PATH", @"D:\Data\test\2.jpg" }}},
new CommandInfo() { Command = CommandInfo.EVENT_CHECKWINDOWEXIST, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "EXIST", "False"} }},
new CommandInfo() { Command = CommandInfo.EVENT_IMAGES_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnUploadZero.bmp" }, { "PATH1", @"assets\btnUploadNoneZero.bmp" } } , SleepAfterEvent = 2},
new CommandInfo() { Command = CommandInfo.EVENT_SETVALUETOUPLOADDLG, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" } , {"PATH", @"D:\Data\test\1.jpg" }}},
new CommandInfo() { Command = CommandInfo.EVENT_CHECKWINDOWEXIST, Parameters = new Dictionary<string, string>() { { "CAPTION", "開啟" }, { "EXIST", "False"} }},
*/
lci.Add(new CommandInfo() { Command = CommandInfo.EVENT_IMAGE_CLICK, Parameters = new Dictionary<string, string>() { { "PATH", @"assets\btnSave.bmp" } }, SetMainBrowserFocus = true, SleepAfterEvent = 10 });
File.WriteAllText(Path.Combine(i_sWorkSpath, $"{i_sWorkingName}.json"), JsonConvert.SerializeObject(lci), Encoding.UTF8);
string[] saOriginPaths = Directory.GetFiles("FBMedia.MyScript");
string sAssetsFolder = Path.Combine(i_sWorkSpath, "assets");
Directory.CreateDirectory(sAssetsFolder);
foreach (string sOriginPath in saOriginPaths)
{
FileInfo fi = new FileInfo(sOriginPath);
string sNewPath = Path.Combine(sAssetsFolder, fi.Name);
File.Copy(sOriginPath, sNewPath);
}
}
while (false);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message);
// Ignore
sMsg = ex.Message;
}
return sMsg;
}
private static string _Action(string i_sURL, string i_sModule, string i_sMethod, out CResponseMessage o_crpResult,
Dictionary<string, object> i_ldicPara)
{
string sMsg;
CResponseMessage crpResult = null;
try
{
do
{
SendWebApiRequest swr = new SendWebApiRequest();
CRequestMessage crm = new CRequestMessage()
{
module = i_sModule,
method = i_sMethod,
param = i_ldicPara,
customparam = new Dictionary<string, object>() { { BLWording.PROGRAMID, "TruckAP" } }
};
CReqestPack crqp = new CReqestPack
{
Reqs = new List<CReqestItem>()
{
new CReqestItem(){ Req = crm }
}
};
sMsg = swr.RunEncryptRequest(i_sURL, crqp, out string sResult);
if (sMsg != null)
{
_log.Error($"Result = {sMsg}");
break;
}
else
{
_log.Info($"Response = {sResult}");
CResponsePack crppResult = JsonConvert.DeserializeObject<CResponsePack>(sResult);
if (crppResult == null)
{
sMsg = "Covert CResponsePack Fail";
break;
}
CResponseMessage crp = crppResult.Reps[0];
if (crp.result == EResponseResult.RR_FALSE)
{
sMsg = crp.msg;
break;
}
crpResult = crp;
}
}
while (false);
}
catch (Exception ex)
{
sMsg = ex.Message;
}
o_crpResult = crpResult;
return sMsg;
}
private void UpdateStatus(string i_sURL, string i_sModule, out CResponseMessage o_crpResult,
Dictionary<string, object> i_dicData, Dictionary<string, object> i_dicWhere)
{
Dictionary<string, object> dicPara = new Dictionary<string, object>
{
{
BLWording.UPD_MASTER,
new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
{ BLWording.DATA, i_dicData },
{ BLWording.WHEREDATA, i_dicWhere }
} }
}
};
_Action(i_sURL, i_sModule, "UpdateStatus", out o_crpResult, dicPara);
}
private string Read(string i_sURL, string i_sModule, out CResponseMessage o_crpResult,
Dictionary<string, object> i_dicWhere)
{
return Query(i_sURL, i_sModule, "Read", out o_crpResult, i_dicWhere);
}
private string Query(string i_sURL, string i_sModule, string i_sAction, out CResponseMessage o_crpResult,
Dictionary<string, object> i_dicWhere = null)
{
Dictionary<string, object> dicPara = new Dictionary<string, object>
{
{
BLWording.QRY_MASTER,
new List<Dictionary<string, object>>() { new Dictionary<string, object>() {
{ BLWording.WHEREDATA, i_dicWhere }
} }
}
};
return _Action(i_sURL, i_sModule, i_sAction, out o_crpResult, dicPara);
}
private static void LoadLog4netConfig()
{
var repository = LogManager.CreateRepository(
Assembly.GetEntryAssembly(),
typeof(log4net.Repository.Hierarchy.Hierarchy)
);
XmlConfigurator.Configure(repository, new FileInfo("Log4Net.config"));
}
private void Form1_Load(object sender, EventArgs e)
{
string sMsg = null;
try
{
string[] saFolders = Directory.GetDirectories(ScriptFolder);
foreach (string sFoder in saFolders)
{
DirectoryInfo di = new DirectoryInfo(sFoder);
if (di.CreationTime.AddDays(3) < DateTime.Now)
{
Directory.Delete(sFoder, true);
}
}
}
catch
{
}
int nIndex = 0;
StringBuilder sb = new StringBuilder($"Form1_Load start! Current directory: {Directory.GetCurrentDirectory()}");
string[] saCmd = Environment.GetCommandLineArgs();
foreach (string sCmd in saCmd)
{
sb.AppendLine($"Para[{nIndex++}] = '{sCmd}'");
}
_log.Info(sb.ToString());
string sForceScript = null;
if (saCmd.Any())
{
for (int nIdx = 0; nIdx < saCmd.Count(); nIdx++)
{
if (saCmd[nIdx] == "-w")
{
sForceScript = saCmd[nIdx + 1];
nIdx++;
}
}
}
try
{
if (sForceScript != null)
{
if (UseOrigtekrpa == "true")
{
RunOrigtekRPAScript(sForceScript);
}
else
{
RunPupetterScript(sForceScript);
}
}
else
{
string sapiurlori = _dicSetting["apiserver"];
string[] saapiurl = sapiurlori.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
_log.Info($"apiserver:{sapiurlori}");
g_lsGroupUidsPost = _uidsInSetting(group_uids_post);
g_lsGroupUidsRPA = _uidsInSetting(group_uids_rpa);
if (g_lsGroupUidsPost.Any() || g_lsGroupUidsRPA.Any())
{
foreach (string sapiurl in saapiurl)
{
g_apiServer = sapiurl;
string sSuffix = "";
foreach (string sCmd in saCmd)
{
if (sCmd == "-a" || sCmd == "-v")
{
sSuffix = sCmd;
break;
}
}
sMsg = Run(sSuffix);
Thread.Sleep(500);
}
}
}
}
catch (Exception ex)
{
sMsg = ex.Message;
}
if (sMsg != null)
{
_log.Info($"Form1_Load end with exception. {sMsg}");
}
else
{
_log.Info($"Form1_Load end Success.");
}
this.Close();
}
private List<string> _uidsInSetting(string i_sKey)
{
List<string> lsUids = new List<string>();
string sSettingValue = _dicSetting[i_sKey];
string[] saUids = sSettingValue.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string sUid in saUids)
{
lsUids.Add(sUid);
_log.Info($"{i_sKey} - group_uid:{sUid}");
}
return lsUids;
}
}
}