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