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