MainWindow.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.Net.Http;
  16. using System.Net.Http.Json;
  17. using Websocket.Client;
  18. using Ookii.Dialogs.Wpf;
  19. using System.Text.Json;
  20. namespace pmtest_client
  21. {
  22. /// <summary>
  23. /// Interaction logic for MainWindow.xaml
  24. /// </summary>
  25. public partial class MainWindow : Window
  26. {
  27. private System.Timers.Timer autoRefreshTimer;
  28. private HttpClient httpClient;
  29. private WebsocketClient? wsClient;
  30. public MainWindow()
  31. {
  32. InitializeComponent();
  33. autoRefreshTimer = new System.Timers.Timer();
  34. autoRefreshTimer.Interval = 1000;
  35. autoRefreshTimer.Elapsed += AutoRefreshTimer_Elapsed;
  36. autoRefreshTimer.Enabled = false;
  37. httpClient = new HttpClient();
  38. }
  39. private void PrintLog(Brush color, String text)
  40. {
  41. Dispatcher.Invoke(() =>
  42. {
  43. Run t = new Run("[" + DateTime.Now.ToString() + "] ");
  44. t.Foreground = Brushes.Navy;
  45. Run tb = new Run(text);
  46. tb.Foreground = color;
  47. logPara.Inlines.Add(t);
  48. logPara.Inlines.Add(tb);
  49. logPara.Inlines.Add(new LineBreak());
  50. rtbLogBox.ScrollToEnd();
  51. });
  52. }
  53. private void AutoRefreshTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
  54. {
  55. DoStatusRefresh();
  56. }
  57. private void btnSetAutoRefresh_Click(object sender, RoutedEventArgs e)
  58. {
  59. autoRefreshTimer?.Start();
  60. }
  61. private void btnManualRefresh_Click(object sender, RoutedEventArgs e)
  62. {
  63. DoStatusRefresh();
  64. }
  65. private void btnStopAutoRefresh_Click(object sender, RoutedEventArgs e)
  66. {
  67. autoRefreshTimer?.Stop();
  68. }
  69. private void DoStatusRefresh()
  70. {
  71. Dispatcher.InvokeAsync(async () =>
  72. {
  73. try
  74. {
  75. httpClient.DefaultRequestHeaders.Remove("AuthKey");
  76. httpClient.DefaultRequestHeaders.Add("AuthKey", tbAccessKey.Text);
  77. HttpResponseMessage response = await httpClient.GetAsync(String.Format("http://{0}/", tbURLRoot.Text));
  78. string responseBody = await response.Content.ReadAsStringAsync();
  79. PrintLog(Brushes.LightBlue, "Status refreshed.");
  80. Dispatcher.Invoke(() =>
  81. {
  82. tbStatusDisplay.Text = responseBody;
  83. });
  84. }
  85. catch (Exception e)
  86. {
  87. PrintLog(Brushes.Crimson, String.Format("Failed do status refresh: {0}", e.Message));
  88. }
  89. });
  90. }
  91. private void btnConnectCmdOut_Click(object sender, RoutedEventArgs e)
  92. {
  93. if (wsClient == null)
  94. {
  95. Dispatcher.InvokeAsync(async () =>
  96. {
  97. try
  98. {
  99. var uri = new Uri(String.Format("ws://{0}/ws/get-cmd-output.satori?auth-key={1}", tbURLRoot.Text, tbAccessKey.Text));
  100. wsClient = new WebsocketClient(uri);
  101. wsClient.IsReconnectionEnabled = false;
  102. wsClient.MessageReceived.Subscribe(msg =>
  103. {
  104. Dispatcher.Invoke(() =>
  105. {
  106. tbCmdOut.AppendText(msg.Text);
  107. });
  108. });
  109. wsClient.DisconnectionHappened.Subscribe(msg =>
  110. {
  111. PrintLog(Brushes.RoyalBlue, "CmdOutput websocket Disconnected.");
  112. wsClient.Dispose();
  113. wsClient = null;
  114. });
  115. PrintLog(Brushes.RoyalBlue, "CmdOuput websocket connecting...");
  116. await wsClient.Start();
  117. PrintLog(Brushes.RoyalBlue, "CmdOuput websocket connected.");
  118. }
  119. catch (Exception err)
  120. {
  121. PrintLog(Brushes.Crimson, string.Format("Websocket error: {0}", err.Message));
  122. }
  123. });
  124. }
  125. }
  126. private void btnDisconnectCmdOut_Click(object sender, RoutedEventArgs e)
  127. {
  128. if (wsClient != null)
  129. {
  130. PrintLog(Brushes.RoyalBlue, "Disconnect CmdOutput websocket connection...");
  131. Dispatcher.InvokeAsync(async () =>
  132. {
  133. await wsClient.Stop(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "stop by user.");
  134. });
  135. }
  136. }
  137. private bool checkApiResponse(Dictionary<string, string> result)
  138. {
  139. if (result.ContainsKey("status"))
  140. {
  141. if (result["status"] == "200")
  142. {
  143. return true;
  144. }
  145. else
  146. {
  147. if (result.ContainsKey("errMsg"))
  148. {
  149. PrintLog(Brushes.Orange, string.Format("API Error: {0}", result["errMsg"]));
  150. PrintLog(Brushes.PaleVioletRed, serializeResponseJson(result));
  151. return false;
  152. }
  153. else
  154. {
  155. PrintLog(Brushes.Orange, "API Error: Unknown Error");
  156. PrintLog(Brushes.PaleVioletRed, serializeResponseJson(result));
  157. return false;
  158. }
  159. }
  160. }
  161. else
  162. {
  163. PrintLog(Brushes.Orange, "Invalid response: 'status' field not found.");
  164. PrintLog(Brushes.PaleVioletRed, serializeResponseJson(result));
  165. return false;
  166. }
  167. }
  168. private string serializeResponseJson(Dictionary<string, string> result)
  169. {
  170. var options = new JsonSerializerOptions { WriteIndented = true };
  171. string jsonString = JsonSerializer.Serialize(result, options);
  172. return jsonString;
  173. }
  174. private void btnCreateTaskDo_Click(object sender, RoutedEventArgs e)
  175. {
  176. JsonDef_Req_CreateTask req = new JsonDef_Req_CreateTask();
  177. req.TaskName = tbCreateTaskName.Text;
  178. req.ExecutablePath = tbCreateTaskExec.Text;
  179. req.WorkDir = tbCreateTaskWDir.Text;
  180. req.Args = CommandLineSplit.SplitArgs(tbCreateTaskArgs.Text);
  181. int etmo = 0;
  182. if (!int.TryParse(tbCreateTaskETmO.Text, out etmo))
  183. {
  184. etmo = 0;
  185. }
  186. req.ExecTimeout = etmo;
  187. Dispatcher.InvokeAsync(async () =>
  188. {
  189. try
  190. {
  191. httpClient.DefaultRequestHeaders.Remove("AuthKey");
  192. httpClient.DefaultRequestHeaders.Add("AuthKey", tbAccessKey.Text);
  193. HttpResponseMessage response = await httpClient.PostAsJsonAsync<JsonDef_Req_CreateTask>(
  194. String.Format("http://{0}/api/new-task.satori", tbURLRoot.Text),
  195. req
  196. );
  197. Dictionary<string, string> result = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
  198. if (result != null)
  199. {
  200. if (checkApiResponse(result))
  201. {
  202. if (result.ContainsKey("cpid") && result.ContainsKey("name"))
  203. {
  204. PrintLog(Brushes.SeaGreen, string.Format("Task created: CPID={0}, Name={1}", result["cpid"], result["name"]));
  205. btnCreateTaskGenNameUUID_Click(null, null);
  206. }
  207. else
  208. {
  209. PrintLog(Brushes.Orange, "Invalid response: missing some fields.");
  210. PrintLog(Brushes.PaleVioletRed, serializeResponseJson(result));
  211. }
  212. }
  213. else
  214. {
  215. return;
  216. }
  217. }
  218. else
  219. {
  220. PrintLog(Brushes.Orange, "Invalid response: null");
  221. }
  222. }
  223. catch (Exception e)
  224. {
  225. PrintLog(Brushes.Crimson, String.Format("Failed create task: {0}", e.Message));
  226. }
  227. });
  228. }
  229. private void btnCreateTaskGenBrowseWorkDir_Click(object sender, RoutedEventArgs e)
  230. {
  231. VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
  232. if (fbd.ShowDialog() == true)
  233. {
  234. tbCreateTaskWDir.Text = fbd.SelectedPath;
  235. }
  236. }
  237. private void btnCreateTaskGenBrowseExec_Click(object sender, RoutedEventArgs e)
  238. {
  239. VistaOpenFileDialog ofd = new VistaOpenFileDialog();
  240. ofd.DefaultExt = ".exe";
  241. ofd.Filter = "exe files|*.exe|All files|*";
  242. if (ofd.ShowDialog() == true)
  243. {
  244. tbCreateTaskExec.Text = ofd.FileName;
  245. }
  246. }
  247. private void btnCreateTaskGenNameUUID_Click(object sender, RoutedEventArgs e)
  248. {
  249. Guid guid = Guid.NewGuid();
  250. tbCreateTaskName.Text = String.Format("task-{0}", guid.ToString());
  251. }
  252. private void btnCreateDaemonBrowseExec_Click(object sender, RoutedEventArgs e)
  253. {
  254. VistaOpenFileDialog ofd = new VistaOpenFileDialog();
  255. ofd.DefaultExt = ".exe";
  256. ofd.Filter = "exe files|*.exe|All files|*";
  257. if (ofd.ShowDialog() == true)
  258. {
  259. tbCreateDaemonExec.Text = ofd.FileName;
  260. }
  261. }
  262. private void btnCreateDaemonBrowseWorkDir_Click(object sender, RoutedEventArgs e)
  263. {
  264. VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
  265. if (fbd.ShowDialog() == true)
  266. {
  267. tbCreateDaemonWDir.Text = fbd.SelectedPath;
  268. }
  269. }
  270. private void btnCreateDaemonDo_Click(object sender, RoutedEventArgs e)
  271. {
  272. JsonDef_Req_CreateDaemon req = new JsonDef_Req_CreateDaemon();
  273. req.DaemonName = tbCreateDaemonName.Text;
  274. req.ExecutablePath = tbCreateDaemonExec.Text;
  275. req.WorkDir = tbCreateDaemonWDir.Text;
  276. req.Args = CommandLineSplit.SplitArgs(tbCreateDaemonArgs.Text);
  277. req.EnableAfterCreate = cbCreateDaemonStartAfterC.IsChecked?.Value;
  278. Dispatcher.InvokeAsync(async () =>
  279. {
  280. try
  281. {
  282. httpClient.DefaultRequestHeaders.Remove("AuthKey");
  283. httpClient.DefaultRequestHeaders.Add("AuthKey", tbAccessKey.Text);
  284. HttpResponseMessage response = await httpClient.PostAsJsonAsync<JsonDef_Req_CreateTask>(
  285. String.Format("http://{0}/api/new-task.satori", tbURLRoot.Text),
  286. req
  287. );
  288. Dictionary<string, string> result = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
  289. if (result != null)
  290. {
  291. if (checkApiResponse(result))
  292. {
  293. if (result.ContainsKey("cpid") && result.ContainsKey("name"))
  294. {
  295. PrintLog(Brushes.SeaGreen, string.Format("Task created: CPID={0}, Name={1}", result["cpid"], result["name"]));
  296. btnCreateTaskGenNameUUID_Click(null, null);
  297. }
  298. else
  299. {
  300. PrintLog(Brushes.Orange, "Invalid response: missing some fields.");
  301. PrintLog(Brushes.PaleVioletRed, serializeResponseJson(result));
  302. }
  303. }
  304. else
  305. {
  306. return;
  307. }
  308. }
  309. else
  310. {
  311. PrintLog(Brushes.Orange, "Invalid response: null");
  312. }
  313. }
  314. catch (Exception e)
  315. {
  316. PrintLog(Brushes.Crimson, String.Format("Failed create task: {0}", e.Message));
  317. }
  318. });
  319. }
  320. private void btnSetDaemonEnable_Click(object sender, RoutedEventArgs e)
  321. {
  322. }
  323. private void btnSetDaemonDisable_Click(object sender, RoutedEventArgs e)
  324. {
  325. }
  326. }
  327. }