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

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