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