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 50 kB

2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. using System.Windows.Shapes;
  23. //using System.Windows.Forms;
  24. using MessageBox = System.Windows.MessageBox;
  25. using Downloader;
  26. namespace starter.viewmodel.settings
  27. {
  28. /// <summary>
  29. /// Settings Window Model
  30. /// </summary>
  31. public class SettingsModel
  32. {
  33. /// <summary>
  34. /// downloader function
  35. /// </summary>
  36. private Data configData = new Data("");
  37. private Tencent_cos_download cloud = new Tencent_cos_download();
  38. private HttpClient client = new HttpClient();
  39. private WebConnect.Web web = new WebConnect.Web();
  40. public SettingsModel()
  41. {
  42. Route = Data.FilePath;
  43. Username = "";
  44. Password = "";
  45. updates = "";
  46. }
  47. /// <summary>
  48. /// save settings
  49. /// </summary>
  50. public bool install()
  51. {
  52. if (Tencent_cos_download.CheckAlreadyDownload())
  53. {
  54. MessageBoxResult repeatOption = MessageBox.Show($"文件已存在于{Downloader.Program.Data.FilePath},是否移动到新位置?", "重复安装", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
  55. // ask if abort install, with warning sign, defalut no;
  56. if (repeatOption == MessageBoxResult.No)
  57. {
  58. Route = Data.FilePath;
  59. return false; // 回到选择地址界面
  60. }
  61. else
  62. {
  63. Downloader.Program.Tencent_cos_download.MoveProgram(Route);
  64. return true;
  65. }
  66. }
  67. else
  68. {
  69. Data.ResetFilepath(Route);
  70. Tencent_cos_download.DownloadAll();
  71. return true;
  72. }
  73. }
  74. public int move()
  75. {
  76. int state = Tencent_cos_download.MoveProgram(Route);
  77. if (state != 0)
  78. Route = Data.FilePath;
  79. return state;
  80. }
  81. ///<summary>
  82. ///check for update
  83. /// </summary>
  84. static bool ProfileAvailable
  85. {
  86. get; set;
  87. }
  88. /// <summary>
  89. /// 检查更新
  90. /// </summary>
  91. /// <returns></returns>
  92. public Status checkUpdate()
  93. {
  94. UpdateInfo updateInfo = Tencent_cos_download.Check();
  95. if (updateInfo.newFileCount == -1)
  96. {
  97. if (updateInfo.changedFileCount == -1)
  98. {
  99. return Status.error;
  100. }
  101. else
  102. {
  103. return Status.disconnected;
  104. }
  105. }
  106. else
  107. {
  108. if (updateInfo.changedFileCount != 0 || updateInfo.newFileCount != 0)
  109. {
  110. Updates = "发现新版本";
  111. }
  112. return Status.menu;
  113. }
  114. }
  115. public void Login()
  116. {
  117. _ = web.LoginToEEsast(client, Username, Password);
  118. }
  119. public bool Update()
  120. {
  121. return Tencent_cos_download.Update();
  122. }
  123. public int Uninst()
  124. {
  125. return Tencent_cos_download.DeleteAll();
  126. }
  127. public bool Launch()
  128. {
  129. if (Tencent_cos_download.CheckAlreadyDownload())
  130. {
  131. Process.Start(System.IO.Path.Combine(Data.FilePath, startName));
  132. return true;
  133. }
  134. else
  135. {
  136. MessageBox.Show($"文件还不存在,请安装主体文件", "文件不存在", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
  137. return false;
  138. }
  139. }
  140. /// <summary>
  141. /// Route of files
  142. /// </summary>
  143. public string Route
  144. {
  145. get; set;
  146. }
  147. public string Username
  148. {
  149. get; set;
  150. }
  151. public string Password
  152. {
  153. get; set;
  154. }
  155. /// <summary>
  156. /// 关于更新的屏幕显示信息
  157. /// </summary>
  158. private string updates;
  159. public string Updates
  160. {
  161. get
  162. {
  163. return updates;
  164. }
  165. set
  166. {
  167. updates = value;
  168. }
  169. }
  170. /// <summary>
  171. /// 关于介绍的屏幕显示信息
  172. /// </summary>
  173. public enum Status { newUser, menu, move, working, disconnected, error, successful, login, web };
  174. public Status status
  175. {
  176. get; set;
  177. }
  178. public bool Working
  179. {
  180. get; set;
  181. }
  182. /// <summary>
  183. /// if an update is planned
  184. /// </summary>
  185. public bool UpdatePlanned
  186. {
  187. get
  188. {
  189. return Program.UpdatePlanned;
  190. }
  191. }
  192. public bool CombatCompleted
  193. {
  194. get
  195. {
  196. return false;
  197. }
  198. }
  199. public bool LoginFailed
  200. {
  201. get; set;
  202. }
  203. }
  204. }
  205. namespace Downloader
  206. {
  207. class Program
  208. {
  209. static List<string> newFileName = new List<string>(); // 新文件名
  210. static List<string> updateFileName = new List<string>(); // 更新文件名
  211. public static string ProgramName = "THUAI6"; // 要运行或下载的程序名称
  212. public static string playerFolder = "player"; // 选手代码保存文件夹路径
  213. public static string startName = "maintest.exe"; // 启动的程序名
  214. public struct UpdateInfo // 更新信息,包括新版本版本号、更改文件数和新文件数
  215. {
  216. public string status;
  217. public int changedFileCount;
  218. public int newFileCount;
  219. }
  220. public static bool UpdatePlanned
  221. {
  222. get; set;
  223. }
  224. static int filenum = 0; // 总文件个数
  225. public class Data
  226. {
  227. public static string path = ""; // 标记路径记录文件THUAI6.json的路径
  228. public static string FilePath = ""; // 最后一级为THUAI6文件夹所在目录
  229. public static string dataPath = ""; // C盘的文档文件夹
  230. public Data(string path)
  231. {
  232. // dataPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  233. dataPath = new DirectoryInfo(".").FullName;
  234. Data.path = System.IO.Path.Combine(dataPath, "THUAI6.json");
  235. if (File.Exists(Data.path))
  236. {
  237. var dict = new Dictionary<string, string>();
  238. using (StreamReader r = new StreamReader(Data.path))
  239. {
  240. string json = r.ReadToEnd();
  241. if (json == null || json == "")
  242. {
  243. json += @"{""THUAI6""" + ":" + @"""2023""}";
  244. }
  245. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  246. if (dict != null && dict.ContainsKey("installpath"))
  247. {
  248. FilePath = dict["installpath"].Replace('\\', '/');
  249. } //读取安装路径
  250. }
  251. dict?.TryAdd("installpath", @path);
  252. using FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  253. using StreamWriter sw = new StreamWriter(fs);
  254. sw.Write(JsonConvert.SerializeObject(dict));
  255. sw.Flush();
  256. }
  257. else
  258. {
  259. FilePath = System.IO.Path.GetDirectoryName(@path);
  260. //将dat文件写入程序运行路径
  261. string json;
  262. Dictionary<string, string> dict = new Dictionary<string, string>();
  263. using FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  264. using (StreamReader r = new StreamReader(fs))
  265. {
  266. json = r.ReadToEnd();
  267. if (json == null || json == "")
  268. {
  269. json += @"{""THUAI6""" + ":" + @"""2023""}";
  270. }
  271. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  272. dict?.Add("installpath", path);
  273. }
  274. using FileStream fs2 = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  275. using StreamWriter sw = new StreamWriter(fs2);
  276. sw.Write(JsonConvert.SerializeObject(dict));
  277. sw.Flush();
  278. }
  279. }
  280. public static void ResetFilepath(string newPath)
  281. {
  282. string json;
  283. Dictionary<string, string> dict = new Dictionary<string, string>();
  284. FilePath = newPath.Replace('\\', '/');
  285. path = System.IO.Path.Combine(dataPath, "THUAI6.json");
  286. using FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  287. using (StreamReader r = new StreamReader(fs))
  288. {
  289. json = r.ReadToEnd();
  290. if (json == null || json == "")
  291. {
  292. json += @"{""THUAI6""" + ":" + @"""2023""}";
  293. }
  294. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  295. if (dict != null && dict.ContainsKey("installpath"))
  296. {
  297. dict["installpath"] = newPath;
  298. }
  299. else
  300. {
  301. dict.Add("installpath", newPath);
  302. }
  303. if (dict == null || !dict.ContainsKey("download"))
  304. {
  305. dict?.Add("download", "true");
  306. }
  307. else
  308. {
  309. dict["download"] = "true";
  310. }
  311. }
  312. using FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
  313. using StreamWriter sw = new StreamWriter(fs2);
  314. fs2.SetLength(0);
  315. sw.Write(JsonConvert.SerializeObject(dict));
  316. sw.Flush();
  317. }
  318. }
  319. public class Tencent_cos_download
  320. {
  321. public void download(string download_dir, string key)
  322. {
  323. // download_dir标记根文件夹路径,key为相对根文件夹的路径(不带./)
  324. // 初始化CosXmlConfig(提供配置SDK接口)
  325. string appid = "1314234950"; // 设置腾讯云账户的账户标识(APPID)
  326. string region = "ap-beijing"; // 设置一个默认的存储桶地域
  327. CosXmlConfig config = new CosXmlConfig.Builder()
  328. .IsHttps(true) // 设置默认 HTTPS 请求
  329. .SetAppid(appid) // 设置腾讯云账户的账户标识 APPID
  330. .SetRegion(region) // 设置一个默认的存储桶地域
  331. .SetDebugLog(true) // 显示日志
  332. .Build(); // 创建 CosXmlConfig 对象
  333. // 永久密钥访问凭证
  334. string secretId = "***"; //"云 API 密钥 SecretId";
  335. string secretKey = "***"; //"云 API 密钥 SecretKey";
  336. long durationSecond = 1000; // 每次请求签名有效时长,单位为秒
  337. QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(
  338. secretId, secretKey, durationSecond
  339. );
  340. // 初始化 CosXmlServer
  341. CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);
  342. // 创建存储桶
  343. try
  344. {
  345. string bucket = "thuai6-1314234950"; // 格式:BucketName-APPID
  346. string localDir = System.IO.Path.GetDirectoryName(download_dir); // 本地文件夹
  347. string localFileName = System.IO.Path.GetFileName(download_dir); // 指定本地保存的文件名
  348. GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName);
  349. Dictionary<string, string> test = request.GetRequestHeaders();
  350. request.SetCosProgressCallback(delegate (long completed, long total)
  351. {
  352. Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
  353. });
  354. // 执行请求
  355. GetObjectResult result = cosXml.GetObject(request);
  356. // 请求成功
  357. }
  358. catch (CosClientException clientEx)
  359. {
  360. throw clientEx;
  361. }
  362. catch (CosServerException serverEx)
  363. {
  364. throw serverEx;
  365. }
  366. }
  367. public static void GetNewHash()
  368. {
  369. Tencent_cos_download Downloader = new Tencent_cos_download();
  370. Downloader.download(System.IO.Path.Combine(Data.FilePath, "hash.json"), "hash.json");
  371. }
  372. public static string GetFileMd5Hash(string strFileFullPath)
  373. {
  374. FileStream fst = null;
  375. try
  376. {
  377. fst = new FileStream(strFileFullPath, FileMode.Open);
  378. byte[] data = MD5.Create().ComputeHash(fst);
  379. StringBuilder sBuilder = new StringBuilder();
  380. for (int i = 0; i < data.Length; i++)
  381. {
  382. sBuilder.Append(data[i].ToString("x2"));
  383. }
  384. fst.Close();
  385. return sBuilder.ToString().ToLower();
  386. }
  387. catch (Exception)
  388. {
  389. if (fst != null)
  390. fst.Close();
  391. return "";
  392. }
  393. finally
  394. {
  395. }
  396. }
  397. public static UpdateInfo Check()
  398. {
  399. string json, MD5, jsonName;
  400. int newFile = 0, updateFile = 0;
  401. newFileName.Clear();
  402. updateFileName.Clear();
  403. jsonName = "hash.json";
  404. UpdateInfo updateInfo;
  405. Tencent_cos_download Downloader = new Tencent_cos_download();
  406. try
  407. {
  408. // 如果json存在就删了重新下
  409. if (File.Exists(System.IO.Path.Combine(Data.FilePath, jsonName)))
  410. {
  411. File.Delete(System.IO.Path.Combine(Data.FilePath, jsonName));
  412. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  413. }
  414. else
  415. {
  416. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  417. }
  418. }
  419. catch (CosClientException clientEx)
  420. {
  421. // 请求失败
  422. updateInfo.status = "ClientEx: " + clientEx.ToString();
  423. updateInfo.newFileCount = -1;
  424. updateInfo.changedFileCount = 0;
  425. return updateInfo;
  426. }
  427. catch (CosServerException serverEx)
  428. {
  429. // 请求失败
  430. updateInfo.status = "ServerEx: " + serverEx.ToString();
  431. updateInfo.newFileCount = -1;
  432. updateInfo.changedFileCount = 0;
  433. return updateInfo;
  434. }
  435. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, jsonName)))
  436. json = r.ReadToEnd();
  437. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  438. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  439. foreach (KeyValuePair<string, string> pair in jsonDict)
  440. {
  441. MD5 = GetFileMd5Hash(System.IO.Path.Combine(Data.FilePath, pair.Key));
  442. if (MD5.Length == 0) // 文档不存在
  443. newFileName.Add(pair.Key);
  444. else if (MD5 != pair.Value) // MD5不匹配
  445. updateFileName.Add(pair.Key);
  446. }
  447. newFile = newFileName.Count;
  448. updateFile = updateFileName.Count;
  449. filenum = newFile + updateFile;
  450. //Console.WriteLine("----------------------" + Environment.NewLine);
  451. if (newFile + updateFile == 0)
  452. {
  453. updateInfo.status = "latest";
  454. updateInfo.newFileCount = 0;
  455. updateInfo.changedFileCount = 0;
  456. newFileName.Clear();
  457. updateFileName.Clear();
  458. }
  459. else
  460. {
  461. updateInfo.status = "old";
  462. //TODO:获取版本号
  463. updateInfo.newFileCount = newFile;
  464. /*
  465. foreach (string filename in newFileName)
  466. {
  467. Console.WriteLine(filename);
  468. }
  469. */
  470. updateInfo.changedFileCount = updateFile;
  471. /*
  472. foreach (string filename in updateFileName)
  473. {
  474. Console.WriteLine(filename);
  475. }
  476. Console.Write(Environment.NewLine + "是否下载新文件? y/n:");
  477. if (Console.Read() != 'y')
  478. Console.WriteLine("下载取消!");
  479. else
  480. Download();
  481. */
  482. UpdatePlanned = true;
  483. }
  484. return updateInfo;
  485. }
  486. public static bool Update()
  487. {
  488. if (UpdatePlanned)
  489. {
  490. Download();
  491. UpdatePlanned = false;
  492. return true;
  493. }
  494. return false;
  495. }
  496. private static void Download()
  497. {
  498. Tencent_cos_download Downloader = new Tencent_cos_download();
  499. int newFile = 0, updateFile = 0;
  500. int totalnew = newFileName.Count, totalupdate = updateFileName.Count;
  501. filenum = totalnew + totalupdate;
  502. if (newFileName.Count > 0 || updateFileName.Count > 0)
  503. {
  504. try
  505. {
  506. foreach (string filename in newFileName)
  507. {
  508. Console.WriteLine(newFile + 1 + "/" + totalnew + ":开始下载" + filename);
  509. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename);
  510. Console.WriteLine(filename + "下载完毕!" + Environment.NewLine);
  511. newFile++;
  512. }
  513. foreach (string filename in updateFileName)
  514. {
  515. Console.WriteLine(updateFile + 1 + "/" + totalupdate + ":开始下载" + filename);
  516. File.Delete(System.IO.Path.Combine(@Data.FilePath, filename));
  517. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename);
  518. Console.WriteLine(filename + "下载完毕!" + Environment.NewLine);
  519. updateFile++;
  520. }
  521. }
  522. catch (CosClientException clientEx)
  523. {
  524. // 请求失败
  525. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  526. return;
  527. }
  528. catch (CosServerException serverEx)
  529. {
  530. // 请求失败
  531. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  532. return;
  533. }
  534. catch (Exception)
  535. {
  536. throw;
  537. }
  538. }
  539. else
  540. Console.WriteLine("当前平台已是最新版本!" + Environment.NewLine);
  541. newFileName.Clear();
  542. updateFileName.Clear();
  543. }
  544. public static bool CheckAlreadyDownload() // 检查是否已经下载
  545. {
  546. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  547. if (!File.Exists(existpath)) // 文件不存在
  548. {
  549. using FileStream fs = new FileStream(existpath, FileMode.Create, FileAccess.ReadWrite);
  550. return false;
  551. }
  552. else // 文件存在
  553. {
  554. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.Read);
  555. using StreamReader sr = new StreamReader(fs);
  556. string json = sr.ReadToEnd();
  557. if (json == null || json == "")
  558. {
  559. json += @"{""THUAI6""" + ":" + @"""2023""}";
  560. }
  561. var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  562. if (dict == null || !dict.ContainsKey("download") || "false" == dict["download"])
  563. {
  564. return false;
  565. }
  566. else if (dict["download"] == "true")
  567. {
  568. return true;
  569. }
  570. else
  571. {
  572. return false;
  573. }
  574. }
  575. }
  576. public static void DownloadAll() // 下载全部文件
  577. {
  578. string jsonName = "hash.json";
  579. string json;
  580. Tencent_cos_download Downloader = new Tencent_cos_download();
  581. try
  582. {
  583. // 如果json存在就删了重新下
  584. if (File.Exists(System.IO.Path.Combine(Data.FilePath, jsonName)))
  585. {
  586. File.Delete(System.IO.Path.Combine(Data.FilePath, jsonName));
  587. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  588. }
  589. else
  590. {
  591. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  592. }
  593. }
  594. catch (CosClientException clientEx)
  595. {
  596. // 请求失败
  597. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  598. return;
  599. }
  600. catch (CosServerException serverEx)
  601. {
  602. // 请求失败
  603. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  604. return;
  605. }
  606. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, jsonName)))
  607. json = r.ReadToEnd();
  608. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  609. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  610. newFileName.Clear();
  611. updateFileName.Clear();
  612. foreach (KeyValuePair<string, string> pair in jsonDict)
  613. {
  614. newFileName.Add(pair.Key);
  615. }
  616. Download();
  617. string json2;
  618. Dictionary<string, string> dict = new Dictionary<string, string>();
  619. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  620. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  621. using (StreamReader r = new StreamReader(fs))
  622. {
  623. json2 = r.ReadToEnd();
  624. if (json2 == null || json2 == "")
  625. {
  626. json2 += @"{""THUAI6""" + ":" + @"""2023""}";
  627. }
  628. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json2);
  629. if (dict == null || !dict.ContainsKey("download"))
  630. {
  631. dict?.Add("download", "true");
  632. }
  633. else
  634. {
  635. dict["download"] = "true";
  636. }
  637. }
  638. using FileStream fs2 = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  639. using StreamWriter sw = new StreamWriter(fs2);
  640. fs2.SetLength(0);
  641. sw.Write(JsonConvert.SerializeObject(dict));
  642. }
  643. public static void Change_all_hash(string topDir, Dictionary<string, string> jsonDict) // 更改HASH
  644. {
  645. DirectoryInfo theFolder = new DirectoryInfo(@topDir);
  646. bool ifexist = false;
  647. // 遍历文件
  648. foreach (FileInfo NextFile in theFolder.GetFiles())
  649. {
  650. string filepath = topDir + @"/" + NextFile.Name; // 文件路径
  651. Console.WriteLine(filepath);
  652. foreach (KeyValuePair<string, string> pair in jsonDict)
  653. {
  654. if (System.IO.Path.Equals(filepath, System.IO.Path.Combine(Data.FilePath, pair.Key).Replace('\\', '/')))
  655. {
  656. ifexist = true;
  657. string MD5 = GetFileMd5Hash(filepath);
  658. jsonDict[pair.Key] = MD5;
  659. }
  660. }
  661. if (!ifexist && NextFile.Name != "hash.json")
  662. {
  663. string MD5 = GetFileMd5Hash(filepath);
  664. string relapath = filepath.Replace(Data.FilePath + '/', string.Empty);
  665. jsonDict.Add(relapath, MD5);
  666. }
  667. ifexist = false;
  668. }
  669. // 遍历文件夹
  670. foreach (DirectoryInfo NextFolder in theFolder.GetDirectories())
  671. {
  672. if (System.IO.Path.Equals(NextFolder.FullName, System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder))))
  673. {
  674. foreach (FileInfo NextFile in NextFolder.GetFiles())
  675. {
  676. if (NextFile.Name == "README.md")
  677. {
  678. string MD5 = GetFileMd5Hash(NextFile.FullName);
  679. string relapath = NextFile.FullName.Replace('\\', '/').Replace(Data.FilePath + '/', string.Empty);
  680. jsonDict.Add(relapath, MD5);
  681. }
  682. }
  683. continue; // 如果是选手文件夹就忽略
  684. }
  685. Change_all_hash(NextFolder.FullName.Replace('\\', '/'), jsonDict);
  686. }
  687. }
  688. public static void UpdateHash()
  689. {
  690. while (true)
  691. {
  692. if (Directory.Exists(Data.FilePath))
  693. {
  694. string json;
  695. if (!File.Exists(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  696. {
  697. Console.WriteLine("hash.json文件丢失!即将重新下载该文件!");
  698. GetNewHash();
  699. }
  700. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  701. json = r.ReadToEnd();
  702. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("/", @"\\");
  703. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  704. Change_all_hash(Data.FilePath, jsonDict);
  705. OverwriteHash(jsonDict);
  706. break;
  707. }
  708. else
  709. {
  710. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  711. Data.ResetFilepath(Console.ReadLine());
  712. }
  713. }
  714. }
  715. public static int DeleteAll()
  716. {
  717. DirectoryInfo di = new DirectoryInfo(Data.FilePath);
  718. DirectoryInfo player = new DirectoryInfo(System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder)));
  719. try
  720. {
  721. foreach (FileInfo file in di.GetFiles())
  722. {
  723. file.Delete();
  724. }
  725. foreach (FileInfo file in player.GetFiles())
  726. {
  727. if (file.Name == "README.md")
  728. {
  729. continue;
  730. }
  731. string filename = System.IO.Path.GetFileName(file.FullName);
  732. file.MoveTo(System.IO.Path.Combine(Data.FilePath, filename));
  733. }
  734. foreach (DirectoryInfo subdi in di.GetDirectories())
  735. {
  736. subdi.Delete(true);
  737. }
  738. }
  739. catch (UnauthorizedAccessException)
  740. {
  741. Console.WriteLine("权限不足,无法删除!");
  742. return -2;
  743. }
  744. catch (DirectoryNotFoundException)
  745. {
  746. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  747. return -3;
  748. }
  749. catch (IOException)
  750. {
  751. Console.WriteLine("文件已经打开,请关闭后再删除");
  752. return -1;
  753. }
  754. string json2;
  755. Dictionary<string, string> dict = new Dictionary<string, string>();
  756. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  757. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  758. using (StreamReader r = new StreamReader(fs))
  759. {
  760. json2 = r.ReadToEnd();
  761. if (json2 == null || json2 == "")
  762. {
  763. json2 += @"{""THUAI6""" + ":" + @"""2023""}";
  764. }
  765. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json2);
  766. if (dict == null || !dict.ContainsKey("download"))
  767. {
  768. dict?.Add("download", "false");
  769. }
  770. else
  771. {
  772. dict["download"] = "false";
  773. }
  774. }
  775. using FileStream fs2 = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  776. using StreamWriter sw = new StreamWriter(fs2);
  777. fs2.SetLength(0);
  778. sw.Write(JsonConvert.SerializeObject(dict));
  779. try
  780. {
  781. File.Delete(Data.path);
  782. }
  783. catch (UnauthorizedAccessException)
  784. {
  785. Console.WriteLine("权限不足,无法删除!");
  786. return -2;
  787. }
  788. catch (DirectoryNotFoundException)
  789. {
  790. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  791. return -3;
  792. }
  793. catch (IOException)
  794. {
  795. Console.WriteLine("文件已经打开,请关闭后再删除");
  796. return -1;
  797. }
  798. Console.WriteLine($"删除成功!player文件夹中的文件已经放在{ProgramName}的根目录下");
  799. return 0;
  800. }
  801. public static void OverwriteHash(Dictionary<string, string> jsonDict)
  802. {
  803. string Contentjson = JsonConvert.SerializeObject(jsonDict);
  804. Contentjson = Contentjson.Replace("\r", String.Empty).Replace("\n", String.Empty).Replace(@"\\", "/");
  805. File.WriteAllText(@System.IO.Path.Combine(Data.FilePath, "hash.json"), Contentjson);
  806. }
  807. public static int MoveProgram(string newPath)
  808. {
  809. DirectoryInfo newdi = new DirectoryInfo(newPath);
  810. DirectoryInfo olddi = new DirectoryInfo(Data.FilePath);
  811. try
  812. {
  813. foreach (DirectoryInfo direct in olddi.GetDirectories())
  814. {
  815. direct.MoveTo(System.IO.Path.Combine(newPath, direct.Name));
  816. }
  817. foreach (FileInfo file in olddi.GetFiles())
  818. {
  819. file.MoveTo(System.IO.Path.Combine(newPath, file.Name));
  820. }
  821. }
  822. catch (DirectoryNotFoundException)
  823. {
  824. Console.WriteLine("原路径未找到!请检查文件是否损坏");
  825. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  826. {
  827. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath, newdirect.Name));
  828. }
  829. foreach (FileInfo file in newdi.GetFiles())
  830. {
  831. file.MoveTo(System.IO.Path.Combine(Data.FilePath, file.Name));
  832. }
  833. Console.WriteLine("移动失败!");
  834. return -2;
  835. }
  836. catch (IOException)
  837. {
  838. Console.WriteLine("文件已打开或者目标路径下有同名文件!");
  839. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  840. {
  841. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath, newdirect.Name));
  842. }
  843. foreach (FileInfo file in newdi.GetFiles())
  844. {
  845. file.MoveTo(System.IO.Path.Combine(Data.FilePath, file.Name));
  846. }
  847. Console.WriteLine("移动失败!");
  848. return -1;
  849. }
  850. Data.ResetFilepath(newPath);
  851. Console.WriteLine("更改路径成功!");
  852. return 0;
  853. }
  854. public static async Task main(string[] args)
  855. {
  856. var client = new HttpClient();
  857. var web = new WebConnect.Web();
  858. Data date = new Data("");
  859. while (true)
  860. {
  861. Console.WriteLine($"1. 更新hash.json 2. 检查更新 3.下载{ProgramName} 4.删除{ProgramName} 5.启动进程 6.移动{ProgramName}到其它路径");
  862. string choose = Console.ReadLine();
  863. if (choose == "1")
  864. {
  865. if (!CheckAlreadyDownload())
  866. {
  867. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  868. continue;
  869. }
  870. UpdateHash();
  871. }
  872. else if (choose == "2")
  873. {
  874. if (!CheckAlreadyDownload())
  875. {
  876. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  877. continue;
  878. }
  879. while (true)
  880. {
  881. if (Data.FilePath != null && Directory.Exists(Data.FilePath))
  882. {
  883. Check();
  884. break;
  885. }
  886. else
  887. {
  888. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  889. Data.ResetFilepath(Console.ReadLine());
  890. }
  891. }
  892. }
  893. else if (choose == "3")
  894. {
  895. if (CheckAlreadyDownload())
  896. {
  897. Console.WriteLine($"已经将{ProgramName}下载到{Data.FilePath}!若要重新下载请先完成删除操作!");
  898. }
  899. else
  900. {
  901. string newpath;
  902. Console.WriteLine("请输入下载路径:");
  903. newpath = Console.ReadLine();
  904. Data.ResetFilepath(newpath);
  905. DownloadAll();
  906. }
  907. }
  908. else if (choose == "4")
  909. {
  910. DeleteAll();
  911. }
  912. else if (choose == "5")
  913. {
  914. if (CheckAlreadyDownload())
  915. {
  916. Process.Start(System.IO.Path.Combine(Data.FilePath, startName));
  917. }
  918. else
  919. {
  920. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  921. }
  922. }
  923. else if (choose == "6")
  924. {
  925. string newPath;
  926. newPath = Console.ReadLine();
  927. MoveProgram(newPath);
  928. }
  929. else if (choose == "7")
  930. {
  931. Console.WriteLine("请输入email:");
  932. string username = Console.ReadLine();
  933. Console.WriteLine("请输入密码:");
  934. string password = Console.ReadLine();
  935. await web.LoginToEEsast(client, username, password);
  936. }
  937. else if (choose == "8")
  938. {
  939. await web.UserDetails(client);
  940. }
  941. else if (choose == "9")
  942. {
  943. await web.UploadFiles(client);
  944. }
  945. else if (choose == "exit")
  946. {
  947. return;
  948. }
  949. }
  950. }
  951. }
  952. }
  953. }
  954. namespace WebConnect
  955. {
  956. class Web
  957. {
  958. public static string logintoken = "";
  959. async public Task LoginToEEsast(HttpClient client, string useremail, string password)
  960. {
  961. string token = "";
  962. using (var response = await client.PostAsync("https://api.eesast.com/users/login", JsonContent.Create(new
  963. {
  964. email = useremail,
  965. password = password,
  966. })))
  967. {
  968. switch (response.StatusCode)
  969. {
  970. case System.Net.HttpStatusCode.OK:
  971. Console.WriteLine("Success login");
  972. token = (System.Text.Json.JsonSerializer.Deserialize(await response.Content.ReadAsStreamAsync(), typeof(LoginResponse), new JsonSerializerOptions()
  973. {
  974. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  975. }) as LoginResponse)
  976. ?.Token ??
  977. throw new Exception("no token!");
  978. logintoken = token;
  979. SaveToken();
  980. break;
  981. default:
  982. int code = ((int)response.StatusCode);
  983. Console.WriteLine(code);
  984. if (code == 401)
  985. {
  986. Console.WriteLine("邮箱或密码错误!");
  987. }
  988. return;
  989. }
  990. }
  991. }
  992. async public Task UploadFiles(HttpClient client) //用来上传文件
  993. {
  994. if (!ReadToken()) //读取token失败
  995. {
  996. return;
  997. }
  998. try
  999. {
  1000. string tarfile; //要上传的文件路径
  1001. string content;
  1002. string filedest; //文件目的地
  1003. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1004. Console.WriteLine("请输入要上传的文件完整路径:");
  1005. tarfile = Console.ReadLine();
  1006. if (!File.Exists(tarfile))
  1007. {
  1008. Console.WriteLine("文件不存在!");
  1009. return;
  1010. }
  1011. Console.WriteLine("要将文件上传到何处?:");
  1012. filedest = Console.ReadLine();
  1013. using FileStream fs = new FileStream(tarfile, FileMode.Open, FileAccess.Read);
  1014. using StreamReader sr = new StreamReader(fs);
  1015. content = sr.ReadToEnd();
  1016. using (var response = await client.PostAsync("https://api.eesast.com/files/upload", JsonContent.Create(new
  1017. {
  1018. file = content,
  1019. dest = filedest
  1020. })))
  1021. {
  1022. switch (response.StatusCode)
  1023. {
  1024. case System.Net.HttpStatusCode.OK:
  1025. Console.WriteLine("上传成功!");
  1026. break;
  1027. case System.Net.HttpStatusCode.Unauthorized:
  1028. Console.WriteLine("您未登录或登录过期,请先登录");
  1029. break;
  1030. default:
  1031. Console.WriteLine("上传失败!");
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. catch (IOException)
  1037. {
  1038. Console.WriteLine("文件读取错误!请检查文件是否被其它应用占用!");
  1039. }
  1040. catch
  1041. {
  1042. Console.WriteLine("请求错误!请检查网络连接!");
  1043. }
  1044. }
  1045. async public Task UserDetails(HttpClient client) // 用来测试访问网站
  1046. {
  1047. if (!ReadToken()) // 读取token失败
  1048. {
  1049. return;
  1050. }
  1051. try
  1052. {
  1053. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1054. Console.WriteLine(logintoken);
  1055. using (var response = await client.GetAsync("https://api.eesast.com/application/info")) // JsonContent.Create(new
  1056. //{
  1057. //})))
  1058. {
  1059. switch (response.StatusCode)
  1060. {
  1061. case System.Net.HttpStatusCode.OK:
  1062. Console.WriteLine("Require OK");
  1063. Console.WriteLine(await response.Content.ReadAsStringAsync());
  1064. break;
  1065. default:
  1066. int code = ((int)response.StatusCode);
  1067. if (code == 401)
  1068. {
  1069. Console.WriteLine("您未登录或登录过期,请先登录");
  1070. }
  1071. return;
  1072. }
  1073. }
  1074. }
  1075. catch
  1076. {
  1077. Console.WriteLine("请求错误!请检查网络连接!");
  1078. }
  1079. }
  1080. public void SaveToken() // 保存token
  1081. {
  1082. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1083. try
  1084. {
  1085. string json;
  1086. Dictionary<string, string> dict = new Dictionary<string, string>();
  1087. using FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1088. using (StreamReader r = new StreamReader(fs))
  1089. {
  1090. json = r.ReadToEnd();
  1091. if (json == null || json == "")
  1092. {
  1093. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1094. }
  1095. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1096. dict?.Add("token", logintoken);
  1097. }
  1098. using FileStream fs2 = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1099. using StreamWriter sw = new StreamWriter(fs2);
  1100. fs2.SetLength(0);
  1101. sw.Write(JsonConvert.SerializeObject(dict)); //将token写入文件
  1102. }
  1103. catch (DirectoryNotFoundException)
  1104. {
  1105. Console.WriteLine("保存token时未找到下载器地址!请检查下载器是否被移动!");
  1106. }
  1107. catch (PathTooLongException)
  1108. {
  1109. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1110. }
  1111. catch (ArgumentNullException)
  1112. {
  1113. Console.WriteLine("下载器路径初始化失败!");
  1114. }
  1115. catch (IOException)
  1116. {
  1117. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  1118. }
  1119. }
  1120. public bool ReadToken() // 读取token
  1121. {
  1122. try
  1123. {
  1124. string json;
  1125. Dictionary<string, string> dict = new Dictionary<string, string>();
  1126. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1127. using FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  1128. using StreamReader sr = new StreamReader(fs);
  1129. json = sr.ReadToEnd();
  1130. if (json == null || json == "")
  1131. {
  1132. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1133. }
  1134. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1135. if (!dict.ContainsKey("token"))
  1136. {
  1137. return false;
  1138. }
  1139. else
  1140. {
  1141. logintoken = dict["token"];
  1142. return true;
  1143. }
  1144. }
  1145. catch (DirectoryNotFoundException)
  1146. {
  1147. Console.WriteLine("读取token时未找到下载器地址!请检查下载器是否被移动!");
  1148. return false;
  1149. }
  1150. catch (FileNotFoundException)
  1151. {
  1152. //没有登陆
  1153. Console.WriteLine("请先登录!");
  1154. return false;
  1155. }
  1156. catch (PathTooLongException)
  1157. {
  1158. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1159. return false;
  1160. }
  1161. catch (ArgumentNullException)
  1162. {
  1163. Console.WriteLine("下载器路径初始化失败!");
  1164. return false;
  1165. }
  1166. catch (IOException)
  1167. {
  1168. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  1169. return false;
  1170. }
  1171. }
  1172. }
  1173. [Serializable]
  1174. record LoginResponse
  1175. {
  1176. // Map `Token` to `token` when serializing
  1177. public string Token { get; set; } = "";
  1178. }
  1179. }