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