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

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