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

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