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

Model.cs 38 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. using COSXML.Auth;
  2. using COSXML.CosException;
  3. using COSXML.Model.Object;
  4. using COSXML;
  5. using Newtonsoft.Json;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System;
  12. using COSXML.Model.Bucket;
  13. using System.Runtime.InteropServices;
  14. using System.Text.Json.Nodes;
  15. using System.Net.Http.Json;
  16. using System.Text.Json;
  17. using System.Xml.Schema;
  18. using static Downloader.Program;
  19. using System.Threading.Tasks;
  20. using System.Net.Http;
  21. using System.Windows;
  22. namespace starter.viewmodel.settings
  23. {
  24. /// <summary>
  25. /// Settings Window Model
  26. /// </summary>
  27. public class SettingsModel
  28. {
  29. /// <summary>
  30. /// downloader function
  31. /// </summary>
  32. private Downloader.Program.Data configData = new Downloader.Program.Data("");
  33. private Downloader.Program.Tencent_cos_download cloud = new Downloader.Program.Tencent_cos_download();
  34. /// <summary>
  35. /// save settings
  36. /// </summary>
  37. public bool install()
  38. {
  39. if (Downloader.Program.Tencent_cos_download.CheckAlreadyDownload())
  40. {
  41. MessageBoxResult repeatOption = MessageBox.Show($"文件已存在于{Downloader.Program.Data.FilePath},是否移动到新位置?", "重复安装", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel);
  42. //ask if abort install, with warning sign, defalut no;
  43. if (repeatOption == MessageBoxResult.Cancel)
  44. {
  45. return false; //回到选择地址界面
  46. }
  47. else if (repeatOption == MessageBoxResult.No)
  48. {
  49. System.Environment.Exit(0);
  50. return false;
  51. }
  52. else
  53. {
  54. Downloader.Program.Tencent_cos_download.MoveProgram(Route);
  55. return true;
  56. }
  57. }
  58. else
  59. {
  60. Downloader.Program.Data.ResetFilepath(Route);
  61. Downloader.Program.Tencent_cos_download.DownloadAll();
  62. return true;
  63. }
  64. }
  65. /// <summary>
  66. /// Route of files
  67. /// </summary>
  68. public string Route
  69. {
  70. get
  71. {
  72. return Downloader.Program.Data.FilePath;
  73. }
  74. set
  75. {
  76. Downloader.Program.Data.FilePath = value;
  77. }
  78. }
  79. /// <summary>
  80. /// if the route was set or is under editing
  81. /// </summary>
  82. public bool EditingRoute
  83. {
  84. get; set;
  85. }
  86. ///<summary>
  87. ///if already installed
  88. /// </summary>
  89. public bool installed
  90. {
  91. get; set;
  92. }
  93. }
  94. }
  95. namespace Downloader
  96. {
  97. class Program
  98. {
  99. static List<string> newFileName = new List<string>(); // 新文件名
  100. static List<string> updateFileName = new List<string>(); // 更新文件名
  101. static string ProgramName = "THUAI6"; // 要运行或下载的程序名称
  102. static string playerFolder = "player"; // 选手代码保存文件夹路径
  103. static string startName = "maintest.exe"; // 启动的程序名
  104. public class Data
  105. {
  106. public static string path = ""; // 标记路径记录文件THUAI6.dat的路径
  107. public static string FilePath = ""; // 最后一级为THUAI6文件夹所在目录
  108. public static string dataPath = ""; // C盘的文档文件夹
  109. public Data(string path)
  110. {
  111. // dataPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  112. dataPath = new DirectoryInfo(".").FullName;
  113. Data.path = System.IO.Path.Combine(dataPath, "THUAI6.dat");
  114. if (File.Exists(Data.path))
  115. {
  116. using (StreamReader r = new StreamReader(Data.path))
  117. FilePath = r.ReadLine().Replace('\\', '/'); // 读取THUAI6.dat文件的第一行
  118. }
  119. else
  120. {
  121. FilePath = System.IO.Path.GetDirectoryName(@path);
  122. // 将dat文件写入程序运行路径
  123. FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  124. StreamWriter sw = new StreamWriter(fs);
  125. sw.Write(path);
  126. sw.Flush();
  127. sw.Close();
  128. }
  129. }
  130. public static void ChangeData(string newLine)
  131. {
  132. if (Directory.Exists(@newLine)) // 判断文件夹是否存在
  133. {
  134. Console.Write($"是否创建新路径 {newLine}?y/n:");
  135. if (Console.Read() != 'y')
  136. {
  137. Console.WriteLine("创建取消!");
  138. return;
  139. }
  140. using (StreamWriter w = new StreamWriter(path))
  141. w.WriteLine(@newLine.Trim('\r').Trim('\n'));
  142. Console.WriteLine($"当前下载路径为{newLine}");
  143. }
  144. }
  145. public static void ResetFilepath(string newPath)
  146. {
  147. FilePath = newPath.Replace('\\', '/');
  148. path = System.IO.Path.Combine(dataPath, "THUAI6.dat");
  149. FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  150. StreamWriter sw = new StreamWriter(fs);
  151. fs.SetLength(0);
  152. sw.Write(newPath);
  153. sw.Flush();
  154. sw.Close();
  155. fs.Close();
  156. }
  157. }
  158. public class Tencent_cos_download
  159. {
  160. public void download(string download_dir, string key)
  161. {
  162. // download_dir标记根文件夹路径,key为相对根文件夹的路径(不带./)
  163. // 初始化CosXmlConfig(提供配置SDK接口)
  164. string appid = "1314234950"; // 设置腾讯云账户的账户标识(APPID)
  165. string region = "ap-beijing"; // 设置一个默认的存储桶地域
  166. CosXmlConfig config = new CosXmlConfig.Builder()
  167. .IsHttps(true) // 设置默认 HTTPS 请求
  168. .SetAppid(appid) // 设置腾讯云账户的账户标识 APPID
  169. .SetRegion(region) // 设置一个默认的存储桶地域
  170. .SetDebugLog(true) // 显示日志
  171. .Build(); // 创建 CosXmlConfig 对象
  172. // 永久密钥访问凭证
  173. string secretId = "***"; //"云 API 密钥 SecretId";
  174. string secretKey = "***"; //"云 API 密钥 SecretKey";
  175. long durationSecond = 1000; // 每次请求签名有效时长,单位为秒
  176. QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(
  177. secretId, secretKey, durationSecond
  178. );
  179. // 初始化 CosXmlServer
  180. CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);
  181. // 创建存储桶
  182. try
  183. {
  184. string bucket = "thuai6-1314234950"; // 格式:BucketName-APPID
  185. string localDir = System.IO.Path.GetDirectoryName(download_dir); // 本地文件夹
  186. string localFileName = System.IO.Path.GetFileName(download_dir); // 指定本地保存的文件名
  187. GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName);
  188. Dictionary<string, string> test = request.GetRequestHeaders();
  189. request.SetCosProgressCallback(delegate (long completed, long total)
  190. {
  191. Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
  192. });
  193. // 执行请求
  194. GetObjectResult result = cosXml.GetObject(request);
  195. // 请求成功
  196. }
  197. catch (CosClientException clientEx)
  198. {
  199. throw clientEx;
  200. }
  201. catch (CosServerException serverEx)
  202. {
  203. throw serverEx;
  204. }
  205. }
  206. public static void GetNewHash()
  207. {
  208. Tencent_cos_download Downloader = new Tencent_cos_download();
  209. Downloader.download(System.IO.Path.Combine(Data.FilePath, "hash.json"), "hash.json");
  210. }
  211. public static string GetFileMd5Hash(string strFileFullPath)
  212. {
  213. FileStream fst = null;
  214. try
  215. {
  216. fst = new FileStream(strFileFullPath, FileMode.Open);
  217. byte[] data = MD5.Create().ComputeHash(fst);
  218. StringBuilder sBuilder = new StringBuilder();
  219. for (int i = 0; i < data.Length; i++)
  220. {
  221. sBuilder.Append(data[i].ToString("x2"));
  222. }
  223. fst.Close();
  224. return sBuilder.ToString().ToLower();
  225. }
  226. catch (Exception)
  227. {
  228. if (fst != null)
  229. fst.Close();
  230. return "";
  231. }
  232. finally
  233. {
  234. }
  235. }
  236. private static void Check()
  237. {
  238. string json, MD5, jsonName;
  239. int newFile = 0, updateFile = 0;
  240. newFileName.Clear();
  241. updateFileName.Clear();
  242. jsonName = "hash.json";
  243. Tencent_cos_download Downloader = new Tencent_cos_download();
  244. try
  245. {
  246. // 如果json存在就删了重新下
  247. if (File.Exists(System.IO.Path.Combine(Data.FilePath, jsonName)))
  248. {
  249. File.Delete(System.IO.Path.Combine(Data.FilePath, jsonName));
  250. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  251. }
  252. else
  253. {
  254. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  255. }
  256. }
  257. catch (CosClientException clientEx)
  258. {
  259. // 请求失败
  260. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  261. return;
  262. }
  263. catch (CosServerException serverEx)
  264. {
  265. // 请求失败
  266. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  267. return;
  268. }
  269. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, jsonName)))
  270. json = r.ReadToEnd();
  271. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  272. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  273. foreach (KeyValuePair<string, string> pair in jsonDict)
  274. {
  275. MD5 = GetFileMd5Hash(System.IO.Path.Combine(Data.FilePath, pair.Key));
  276. if (MD5.Length == 0) // 文档不存在
  277. newFileName.Add(pair.Key);
  278. else if (MD5 != pair.Value) // MD5不匹配
  279. updateFileName.Add(pair.Key);
  280. }
  281. newFile = newFileName.Count;
  282. updateFile = updateFileName.Count;
  283. Console.WriteLine("----------------------" + Environment.NewLine);
  284. if (newFile + updateFile == 0)
  285. {
  286. Console.WriteLine("当前平台已是最新版本!" + Environment.NewLine);
  287. newFileName.Clear();
  288. updateFileName.Clear();
  289. }
  290. else
  291. {
  292. Console.WriteLine($"发现{newFile}个新文件" + Environment.NewLine);
  293. foreach (string filename in newFileName)
  294. {
  295. Console.WriteLine(filename);
  296. }
  297. Console.WriteLine(Environment.NewLine + $"发现{updateFile}个文件更新" + Environment.NewLine);
  298. foreach (string filename in updateFileName)
  299. {
  300. Console.WriteLine(filename);
  301. }
  302. Console.Write(Environment.NewLine + "是否下载新文件? y/n:");
  303. if (Console.Read() != 'y')
  304. Console.WriteLine("下载取消!");
  305. else
  306. Download();
  307. }
  308. }
  309. private static void Download()
  310. {
  311. Tencent_cos_download Downloader = new Tencent_cos_download();
  312. int newFile = 0, updateFile = 0;
  313. int totalnew = newFileName.Count, totalupdate = updateFileName.Count;
  314. if (newFileName.Count > 0 || updateFileName.Count > 0)
  315. {
  316. try
  317. {
  318. foreach (string filename in newFileName)
  319. {
  320. Console.WriteLine(newFile + 1 + "/" + totalnew + ":开始下载" + filename);
  321. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename);
  322. Console.WriteLine(filename + "下载完毕!" + Environment.NewLine);
  323. newFile++;
  324. }
  325. foreach (string filename in updateFileName)
  326. {
  327. Console.WriteLine(updateFile + 1 + "/" + totalupdate + ":开始下载" + filename);
  328. File.Delete(System.IO.Path.Combine(@Data.FilePath, filename));
  329. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename);
  330. Console.WriteLine(filename + "下载完毕!" + Environment.NewLine);
  331. updateFile++;
  332. }
  333. }
  334. catch (CosClientException clientEx)
  335. {
  336. // 请求失败
  337. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  338. return;
  339. }
  340. catch (CosServerException serverEx)
  341. {
  342. // 请求失败
  343. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  344. return;
  345. }
  346. catch (Exception)
  347. {
  348. throw;
  349. }
  350. }
  351. else
  352. Console.WriteLine("当前平台已是最新版本!" + Environment.NewLine);
  353. newFileName.Clear();
  354. updateFileName.Clear();
  355. }
  356. public static bool CheckAlreadyDownload() // 检查是否已经下载
  357. {
  358. string existpath = System.IO.Path.Combine(Data.dataPath, "Exists.txt");
  359. if (!File.Exists(existpath)) // 文件不存在
  360. {
  361. FileStream fs = new FileStream(existpath, FileMode.Create, FileAccess.ReadWrite);
  362. fs.Close();
  363. return false;
  364. }
  365. else // 文件存在
  366. {
  367. FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.Read);
  368. StreamReader sr = new StreamReader(fs);
  369. if ("true" == sr.ReadLine())
  370. {
  371. sr.Close();
  372. fs.Close();
  373. return true;
  374. }
  375. else
  376. {
  377. sr.Close();
  378. fs.Close();
  379. return false;
  380. }
  381. }
  382. }
  383. public static void DownloadAll() // 下载全部文件
  384. {
  385. string jsonName = "hash.json";
  386. string json;
  387. Tencent_cos_download Downloader = new Tencent_cos_download();
  388. try
  389. {
  390. // 如果json存在就删了重新下
  391. if (File.Exists(System.IO.Path.Combine(Data.FilePath, jsonName)))
  392. {
  393. File.Delete(System.IO.Path.Combine(Data.FilePath, jsonName));
  394. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  395. }
  396. else
  397. {
  398. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  399. }
  400. }
  401. catch (CosClientException clientEx)
  402. {
  403. // 请求失败
  404. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  405. return;
  406. }
  407. catch (CosServerException serverEx)
  408. {
  409. // 请求失败
  410. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  411. return;
  412. }
  413. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, jsonName)))
  414. json = r.ReadToEnd();
  415. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  416. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  417. newFileName.Clear();
  418. updateFileName.Clear();
  419. foreach (KeyValuePair<string, string> pair in jsonDict)
  420. {
  421. newFileName.Add(pair.Key);
  422. }
  423. Download();
  424. string existpath = System.IO.Path.Combine(Data.dataPath, "Exists.txt");
  425. FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  426. StreamWriter sw = new StreamWriter(fs);
  427. fs.SetLength(0);
  428. sw.Write("true");
  429. sw.Close();
  430. fs.Close();
  431. }
  432. public static void Change_all_hash(string topDir, Dictionary<string, string> jsonDict) // 更改HASH
  433. {
  434. DirectoryInfo theFolder = new DirectoryInfo(@topDir);
  435. bool ifexist = false;
  436. // 遍历文件
  437. foreach (FileInfo NextFile in theFolder.GetFiles())
  438. {
  439. string filepath = topDir + @"/" + NextFile.Name; // 文件路径
  440. Console.WriteLine(filepath);
  441. foreach (KeyValuePair<string, string> pair in jsonDict)
  442. {
  443. if (System.IO.Path.Equals(filepath, System.IO.Path.Combine(Data.FilePath, pair.Key).Replace('\\', '/')))
  444. {
  445. ifexist = true;
  446. string MD5 = GetFileMd5Hash(filepath);
  447. jsonDict[pair.Key] = MD5;
  448. }
  449. }
  450. if (!ifexist && NextFile.Name != "hash.json")
  451. {
  452. string MD5 = GetFileMd5Hash(filepath);
  453. string relapath = filepath.Replace(Data.FilePath + '/', string.Empty);
  454. jsonDict.Add(relapath, MD5);
  455. }
  456. ifexist = false;
  457. }
  458. // 遍历文件夹
  459. foreach (DirectoryInfo NextFolder in theFolder.GetDirectories())
  460. {
  461. if (System.IO.Path.Equals(NextFolder.FullName, System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder))))
  462. {
  463. foreach (FileInfo NextFile in NextFolder.GetFiles())
  464. {
  465. if (NextFile.Name == "README.md")
  466. {
  467. string MD5 = GetFileMd5Hash(NextFile.FullName);
  468. string relapath = NextFile.FullName.Replace('\\', '/').Replace(Data.FilePath + '/', string.Empty);
  469. jsonDict.Add(relapath, MD5);
  470. }
  471. }
  472. continue; // 如果是选手文件夹就忽略
  473. }
  474. Change_all_hash(NextFolder.FullName.Replace('\\', '/'), jsonDict);
  475. }
  476. }
  477. public static void UpdateHash()
  478. {
  479. while (true)
  480. {
  481. if (Directory.Exists(Data.FilePath))
  482. {
  483. string json;
  484. if (!File.Exists(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  485. {
  486. Console.WriteLine("hash.json文件丢失!即将重新下载该文件!");
  487. GetNewHash();
  488. }
  489. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  490. json = r.ReadToEnd();
  491. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("/", @"\\");
  492. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  493. Change_all_hash(Data.FilePath, jsonDict);
  494. OverwriteHash(jsonDict);
  495. break;
  496. }
  497. else
  498. {
  499. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  500. Data.ResetFilepath(Console.ReadLine());
  501. }
  502. }
  503. }
  504. public static void DeleteAll()
  505. {
  506. DirectoryInfo di = new DirectoryInfo(Data.FilePath);
  507. DirectoryInfo player = new DirectoryInfo(System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder)));
  508. try
  509. {
  510. foreach (FileInfo file in di.GetFiles())
  511. {
  512. file.Delete();
  513. }
  514. foreach (FileInfo file in player.GetFiles())
  515. {
  516. if (file.Name == "README.md")
  517. {
  518. continue;
  519. }
  520. string filename = System.IO.Path.GetFileName(file.FullName);
  521. file.MoveTo(System.IO.Path.Combine(Data.FilePath, filename));
  522. }
  523. foreach (DirectoryInfo subdi in di.GetDirectories())
  524. {
  525. subdi.Delete(true);
  526. }
  527. }
  528. catch (UnauthorizedAccessException)
  529. {
  530. Console.WriteLine("权限不足,无法删除!");
  531. return;
  532. }
  533. catch (DirectoryNotFoundException)
  534. {
  535. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  536. return;
  537. }
  538. catch (IOException)
  539. {
  540. Console.WriteLine("文件已经打开,请关闭后再删除");
  541. return;
  542. }
  543. string existpath = System.IO.Path.Combine(Data.dataPath, "Exists.txt");
  544. FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  545. StreamWriter sw = new StreamWriter(fs);
  546. fs.SetLength(0);
  547. sw.Write("false");
  548. sw.Close();
  549. fs.Close();
  550. try
  551. {
  552. File.Delete(Data.path);
  553. }
  554. catch (UnauthorizedAccessException)
  555. {
  556. Console.WriteLine("权限不足,无法删除!");
  557. return;
  558. }
  559. catch (DirectoryNotFoundException)
  560. {
  561. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  562. return;
  563. }
  564. catch (IOException)
  565. {
  566. Console.WriteLine("文件已经打开,请关闭后再删除");
  567. return;
  568. }
  569. Console.WriteLine($"删除成功!player文件夹中的文件已经放在{ProgramName}的根目录下");
  570. }
  571. public static void OverwriteHash(Dictionary<string, string> jsonDict)
  572. {
  573. string Contentjson = JsonConvert.SerializeObject(jsonDict);
  574. Contentjson = Contentjson.Replace("\r", String.Empty).Replace("\n", String.Empty).Replace(@"\\", "/");
  575. File.WriteAllText(@System.IO.Path.Combine(Data.FilePath, "hash.json"), Contentjson);
  576. }
  577. public static void MoveProgram(string newPath)
  578. {
  579. DirectoryInfo newdi = new DirectoryInfo(newPath);
  580. DirectoryInfo olddi = new DirectoryInfo(Data.FilePath);
  581. try
  582. {
  583. foreach (DirectoryInfo direct in olddi.GetDirectories())
  584. {
  585. direct.MoveTo(System.IO.Path.Combine(newPath, direct.Name));
  586. }
  587. foreach (FileInfo file in olddi.GetFiles())
  588. {
  589. file.MoveTo(System.IO.Path.Combine(newPath, file.Name));
  590. }
  591. }
  592. catch (DirectoryNotFoundException)
  593. {
  594. Console.WriteLine("原路径未找到!请检查文件是否损坏");
  595. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  596. {
  597. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath, newdirect.Name));
  598. }
  599. foreach (FileInfo file in newdi.GetFiles())
  600. {
  601. file.MoveTo(System.IO.Path.Combine(Data.FilePath, file.Name));
  602. }
  603. Console.WriteLine("移动失败!");
  604. }
  605. catch (IOException)
  606. {
  607. Console.WriteLine("文件已打开或者目标路径下有同名文件!");
  608. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  609. {
  610. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath, newdirect.Name));
  611. }
  612. foreach (FileInfo file in newdi.GetFiles())
  613. {
  614. file.MoveTo(System.IO.Path.Combine(Data.FilePath, file.Name));
  615. }
  616. Console.WriteLine("移动失败!");
  617. }
  618. Data.ResetFilepath(newPath);
  619. Console.WriteLine("更改路径成功!");
  620. }
  621. public static async Task main(string[] args)
  622. {
  623. var client = new HttpClient();
  624. var web = new WebConnect.Web();
  625. Data date = new Data("");
  626. while (true)
  627. {
  628. Console.WriteLine($"1. 更新hash.json 2. 检查更新 3.下载{ProgramName} 4.删除{ProgramName} 5.启动进程 6.移动{ProgramName}到其它路径");
  629. string choose = Console.ReadLine();
  630. if (choose == "1")
  631. {
  632. if (!CheckAlreadyDownload())
  633. {
  634. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  635. continue;
  636. }
  637. UpdateHash();
  638. }
  639. else if (choose == "2")
  640. {
  641. if (!CheckAlreadyDownload())
  642. {
  643. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  644. continue;
  645. }
  646. while (true)
  647. {
  648. if (Data.FilePath != null && Directory.Exists(Data.FilePath))
  649. {
  650. Check();
  651. break;
  652. }
  653. else
  654. {
  655. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  656. Data.ResetFilepath(Console.ReadLine());
  657. }
  658. }
  659. }
  660. else if (choose == "3")
  661. {
  662. if (CheckAlreadyDownload())
  663. {
  664. Console.WriteLine($"已经将{ProgramName}下载到{Data.FilePath}!若要重新下载请先完成删除操作!");
  665. }
  666. else
  667. {
  668. string newpath;
  669. Console.WriteLine("请输入下载路径:");
  670. newpath = Console.ReadLine();
  671. Data.ResetFilepath(newpath);
  672. DownloadAll();
  673. }
  674. }
  675. else if (choose == "4")
  676. {
  677. DeleteAll();
  678. }
  679. else if (choose == "5")
  680. {
  681. if (CheckAlreadyDownload())
  682. {
  683. Process.Start(System.IO.Path.Combine(Data.FilePath, startName));
  684. }
  685. else
  686. {
  687. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  688. }
  689. }
  690. else if (choose == "6")
  691. {
  692. string newPath;
  693. newPath = Console.ReadLine();
  694. MoveProgram(newPath);
  695. }
  696. else if (choose == "7")
  697. {
  698. Console.WriteLine("请输入email:");
  699. string username = Console.ReadLine();
  700. Console.WriteLine("请输入密码:");
  701. string password = Console.ReadLine();
  702. await web.LoginToEEsast(client, username, password);
  703. }
  704. else if (choose == "8")
  705. {
  706. await web.UserDetails(client);
  707. }
  708. else if (choose == "exit")
  709. {
  710. return;
  711. }
  712. }
  713. }
  714. }
  715. }
  716. }
  717. namespace WebConnect
  718. {
  719. class Web
  720. {
  721. public static string logintoken = "";
  722. async public Task LoginToEEsast(HttpClient client, string useremail, string password)
  723. {
  724. string token = "";
  725. using (var response = await client.PostAsync("https://api.eesast.com/users/login", JsonContent.Create(new
  726. {
  727. email = useremail,
  728. password = password,
  729. })))
  730. {
  731. switch (response.StatusCode)
  732. {
  733. case System.Net.HttpStatusCode.OK:
  734. Console.WriteLine("Success login");
  735. token = (System.Text.Json.JsonSerializer.Deserialize(await response.Content.ReadAsStreamAsync(), typeof(LoginResponse), new JsonSerializerOptions()
  736. {
  737. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  738. }) as LoginResponse)?.Token ?? throw new Exception("no token!");
  739. logintoken = token;
  740. SaveToken();
  741. break;
  742. default:
  743. int code = ((int)response.StatusCode);
  744. Console.WriteLine(code);
  745. if (code == 401)
  746. {
  747. Console.WriteLine("邮箱或密码错误!");
  748. }
  749. return;
  750. }
  751. }
  752. }
  753. async public Task UserDetails(HttpClient client) //用来测试访问网站
  754. {
  755. if (!ReadToken()) //读取token失败
  756. {
  757. return;
  758. }
  759. try
  760. {
  761. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  762. Console.WriteLine(logintoken);
  763. using (var response = await client.GetAsync("https://api.eesast.com/application/info")) //JsonContent.Create(new
  764. //{
  765. //})))
  766. {
  767. switch (response.StatusCode)
  768. {
  769. case System.Net.HttpStatusCode.OK:
  770. Console.WriteLine("Require OK");
  771. Console.WriteLine(await response.Content.ReadAsStringAsync());
  772. break;
  773. default:
  774. int code = ((int)response.StatusCode);
  775. if (code == 401)
  776. {
  777. Console.WriteLine("您未登录或登录过期,请先登录");
  778. }
  779. return;
  780. }
  781. }
  782. }
  783. catch
  784. {
  785. Console.WriteLine("请求错误!请检查网络连接!");
  786. }
  787. }
  788. public void SaveToken()//保存token
  789. {
  790. string savepath = Path.Combine(Data.dataPath, "Token.dat");
  791. try
  792. {
  793. FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  794. StreamWriter sw = new StreamWriter(fs);
  795. fs.SetLength(0);
  796. sw.Write(logintoken); //将token写入文件
  797. sw.Close();
  798. fs.Close();
  799. }
  800. catch (DirectoryNotFoundException)
  801. {
  802. Console.WriteLine("保存token时未找到下载器地址!请检查下载器是否被移动!");
  803. }
  804. catch (PathTooLongException)
  805. {
  806. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  807. }
  808. catch (ArgumentNullException)
  809. {
  810. Console.WriteLine("下载器路径初始化失败!");
  811. }
  812. catch (IOException)
  813. {
  814. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  815. }
  816. }
  817. public bool ReadToken()//读取token
  818. {
  819. try
  820. {
  821. string savepath = Path.Combine(Data.dataPath, "Token.dat");
  822. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  823. StreamReader sr = new StreamReader(fs);
  824. logintoken = sr.ReadLine();
  825. sr.Close();
  826. fs.Close();
  827. return true;
  828. }
  829. catch (DirectoryNotFoundException)
  830. {
  831. Console.WriteLine("读取token时未找到下载器地址!请检查下载器是否被移动!");
  832. return false;
  833. }
  834. catch (FileNotFoundException)
  835. {
  836. //没有登陆
  837. Console.WriteLine("请先登陆!");
  838. return false;
  839. }
  840. catch (PathTooLongException)
  841. {
  842. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  843. return false;
  844. }
  845. catch (ArgumentNullException)
  846. {
  847. Console.WriteLine("下载器路径初始化失败!");
  848. return false;
  849. }
  850. catch (IOException)
  851. {
  852. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  853. return false;
  854. }
  855. }
  856. }
  857. [Serializable]
  858. record LoginResponse
  859. {
  860. // Map `Token` to `token` when serializing
  861. public string Token { get; set; } = "";
  862. }
  863. }