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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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 = "AKIDvhEVXN4cv0ugIlFYiniV6Wk1McfkplYA"; //"云 API 密钥 SecretId";
  341. string secretKey = "YyGLGCJG4f5VsEUddnz9JSRPSSK8sYBo"; //"云 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. string filedest; //文件目的地
  1014. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1015. Console.WriteLine("请输入要上传的文件完整路径:");
  1016. tarfile = Console.ReadLine();
  1017. if (!File.Exists(tarfile))
  1018. {
  1019. Console.WriteLine("文件不存在!");
  1020. return;
  1021. }
  1022. Console.WriteLine("请选择语言类型:1.C++ 2.python");
  1023. string type = Console.ReadLine();
  1024. if (type == "1")
  1025. {
  1026. type = "cpp";
  1027. }
  1028. else if (type == "2")
  1029. {
  1030. type = "python";
  1031. }
  1032. else
  1033. {
  1034. return;
  1035. }
  1036. Console.WriteLine("请确认这是哪个玩家的代码:1.player_1 2.player_2 3.player_3 4.player_4");
  1037. string plr = Console.ReadLine();
  1038. if (plr == "1")
  1039. {
  1040. plr = "player_1";
  1041. }
  1042. else if (plr == "2")
  1043. {
  1044. plr = "player_2";
  1045. }
  1046. else if (plr == "3")
  1047. {
  1048. plr = "player_3";
  1049. }
  1050. else if (plr == "4")
  1051. {
  1052. plr = "player_4";
  1053. }
  1054. else
  1055. {
  1056. return;
  1057. }
  1058. using FileStream fs = new FileStream(tarfile, FileMode.Open, FileAccess.Read);
  1059. using StreamReader sr = new StreamReader(fs);
  1060. content = sr.ReadToEnd();
  1061. using (var response = await client.GetAsync($"https://api.eesast.com/static/player?team_id={GetTeamId()}"))
  1062. {
  1063. switch (response.StatusCode)
  1064. {
  1065. case System.Net.HttpStatusCode.OK:
  1066. var res = JsonConvert.DeserializeObject<Dictionary<string, string>>(await response.Content.ReadAsStringAsync());
  1067. string appid = "1255334966"; // 设置腾讯云账户的账户标识(APPID)
  1068. string region = "ap-beijing"; // 设置一个默认的存储桶地域
  1069. CosXmlConfig config = new CosXmlConfig.Builder()
  1070. .IsHttps(true) // 设置默认 HTTPS 请求
  1071. .SetAppid(appid) // 设置腾讯云账户的账户标识 APPID
  1072. .SetRegion(region) // 设置一个默认的存储桶地域
  1073. .SetDebugLog(true) // 显示日志
  1074. .Build(); // 创建 CosXmlConfig 对象
  1075. string tmpSecretId = res["TmpSecretId"]; //"临时密钥 SecretId";
  1076. string tmpSecretKey = res["TmpSecretKey"]; //"临时密钥 SecretKey";
  1077. string tmpToken = res["SecurityToken"]; //"临时密钥 token";
  1078. long tmpExpiredTime = Convert.ToInt64(res["ExpiredTime"]);//临时密钥有效截止时间,精确到秒
  1079. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  1080. tmpSecretId, tmpSecretKey, tmpExpiredTime, tmpToken
  1081. );
  1082. // 初始化 CosXmlServer
  1083. CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);
  1084. // 初始化 TransferConfig
  1085. TransferConfig transferConfig = new TransferConfig();
  1086. // 初始化 TransferManager
  1087. TransferManager transferManager = new TransferManager(cosXml, transferConfig);
  1088. string bucket = "eesast-1255334966"; //存储桶,格式:BucketName-APPID
  1089. string cosPath = $"/THUAI6/{GetTeamId()}/{type}/{plr}"; //对象在存储桶中的位置标识符,即称对象键
  1090. string srcPath = tarfile;//本地文件绝对路径
  1091. // 上传对象
  1092. COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);
  1093. uploadTask.SetSrcPath(srcPath);
  1094. uploadTask.progressCallback = delegate (long completed, long total)
  1095. {
  1096. Console.WriteLine(string.Format("progress = {0:##.##}%", completed * 100.0 / total));
  1097. };
  1098. try
  1099. {
  1100. COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask);
  1101. Console.WriteLine(result.GetResultInfo());
  1102. string eTag = result.eTag;
  1103. //到这里应该是成功了,但是因为我没有试过,也不知道具体情况,可能还要根据result的内容判断
  1104. }
  1105. catch (Exception e)
  1106. {
  1107. Console.WriteLine("CosException: " + e);
  1108. }
  1109. break;
  1110. case System.Net.HttpStatusCode.Unauthorized:
  1111. Console.WriteLine("您未登录或登录过期,请先登录");
  1112. break;
  1113. default:
  1114. Console.WriteLine("上传失败!");
  1115. break;
  1116. }
  1117. }
  1118. }
  1119. catch (IOException)
  1120. {
  1121. Console.WriteLine("文件读取错误!请检查文件是否被其它应用占用!");
  1122. }
  1123. catch
  1124. {
  1125. Console.WriteLine("请求错误!请检查网络连接!");
  1126. }
  1127. }
  1128. async public Task UserDetails(HttpClient client) // 用来测试访问网站
  1129. {
  1130. if (!ReadToken()) // 读取token失败
  1131. {
  1132. return;
  1133. }
  1134. try
  1135. {
  1136. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1137. Console.WriteLine(logintoken);
  1138. using (var response = await client.GetAsync("https://api.eesast.com/application/info")) // JsonContent.Create(new
  1139. //{
  1140. //})))
  1141. {
  1142. switch (response.StatusCode)
  1143. {
  1144. case System.Net.HttpStatusCode.OK:
  1145. Console.WriteLine("Require OK");
  1146. Console.WriteLine(await response.Content.ReadAsStringAsync());
  1147. break;
  1148. default:
  1149. int code = ((int)response.StatusCode);
  1150. if (code == 401)
  1151. {
  1152. Console.WriteLine("您未登录或登录过期,请先登录");
  1153. }
  1154. return;
  1155. }
  1156. }
  1157. }
  1158. catch
  1159. {
  1160. Console.WriteLine("请求错误!请检查网络连接!");
  1161. }
  1162. }
  1163. public void SaveToken() // 保存token
  1164. {
  1165. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1166. try
  1167. {
  1168. string json;
  1169. Dictionary<string, string> dict = new Dictionary<string, string>();
  1170. using FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1171. using (StreamReader r = new StreamReader(fs))
  1172. {
  1173. json = r.ReadToEnd();
  1174. if (json == null || json == "")
  1175. {
  1176. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1177. }
  1178. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1179. dict?.Add("token", logintoken);
  1180. }
  1181. using FileStream fs2 = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1182. using StreamWriter sw = new StreamWriter(fs2);
  1183. fs2.SetLength(0);
  1184. sw.Write(JsonConvert.SerializeObject(dict)); //将token写入文件
  1185. }
  1186. catch (DirectoryNotFoundException)
  1187. {
  1188. Console.WriteLine("保存token时未找到下载器地址!请检查下载器是否被移动!");
  1189. }
  1190. catch (PathTooLongException)
  1191. {
  1192. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1193. }
  1194. catch (ArgumentNullException)
  1195. {
  1196. Console.WriteLine("下载器路径初始化失败!");
  1197. }
  1198. catch (IOException)
  1199. {
  1200. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  1201. }
  1202. }
  1203. public bool ReadToken() // 读取token
  1204. {
  1205. try
  1206. {
  1207. string json;
  1208. Dictionary<string, string> dict = new Dictionary<string, string>();
  1209. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1210. using FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  1211. using StreamReader sr = new StreamReader(fs);
  1212. json = sr.ReadToEnd();
  1213. if (json == null || json == "")
  1214. {
  1215. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1216. }
  1217. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1218. if (!dict.ContainsKey("token"))
  1219. {
  1220. return false;
  1221. }
  1222. else
  1223. {
  1224. logintoken = dict["token"];
  1225. return true;
  1226. }
  1227. }
  1228. catch (DirectoryNotFoundException)
  1229. {
  1230. Console.WriteLine("读取token时未找到下载器地址!请检查下载器是否被移动!");
  1231. return false;
  1232. }
  1233. catch (FileNotFoundException)
  1234. {
  1235. //没有登陆
  1236. Console.WriteLine("请先登录!");
  1237. return false;
  1238. }
  1239. catch (PathTooLongException)
  1240. {
  1241. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1242. return false;
  1243. }
  1244. catch (ArgumentNullException)
  1245. {
  1246. Console.WriteLine("下载器路径初始化失败!");
  1247. return false;
  1248. }
  1249. catch (IOException)
  1250. {
  1251. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  1252. return false;
  1253. }
  1254. }
  1255. async public Task<string> GetTeamId()
  1256. {
  1257. var client = new HttpClient();
  1258. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  1259. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  1260. var content = new StringContent("{\"query\":\"query MyQuery {\r\n contest_team_member(where: {user_id: {_eq: \""
  1261. + Downloader.UserInfo._id + "\"}}) {\r\n team_id\r\n }\r\n}\r\n\",\"variables\":{}}", null, "application/json");
  1262. request.Content = content;
  1263. var response = await client.SendAsync(request);
  1264. response.EnsureSuccessStatusCode();
  1265. return await response.Content.ReadAsStringAsync();
  1266. }
  1267. async public Task<string> GetUserId(string learnNumber)
  1268. {
  1269. var client = new HttpClient();
  1270. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  1271. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  1272. var content = new StringContent("{\"query\":\"query MyQuery {\r\n user(where: {id: {_eq: \""
  1273. + learnNumber + "\"}}) {\r\n _id\r\n }\r\n}\r\n\",\"variables\":{}}", null, "application/json");
  1274. request.Content = content;
  1275. var response = await client.SendAsync(request);
  1276. response.EnsureSuccessStatusCode();
  1277. return await response.Content.ReadAsStringAsync();
  1278. }
  1279. }
  1280. [Serializable]
  1281. record LoginResponse
  1282. {
  1283. // Map `Token` to `token` when serializing
  1284. public string Token { get; set; } = "";
  1285. }
  1286. }