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

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