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 72 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  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. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  659. return;
  660. }
  661. catch (CosServerException serverEx)
  662. {
  663. // 请求失败
  664. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  665. return;
  666. }
  667. catch (Exception)
  668. {
  669. throw;
  670. }
  671. }
  672. else
  673. Console.WriteLine("当前平台已是最新版本!" + Environment.NewLine);
  674. newFileName.Clear();
  675. updateFileName.Clear();
  676. }
  677. public static bool CheckAlreadyDownload() // 检查是否已经下载
  678. {
  679. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  680. if (!File.Exists(existpath)) // 文件不存在
  681. {
  682. using FileStream fs = new FileStream(existpath, FileMode.Create, FileAccess.ReadWrite);
  683. return false;
  684. }
  685. else // 文件存在
  686. {
  687. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.Read);
  688. using StreamReader sr = new StreamReader(fs);
  689. string json = sr.ReadToEnd();
  690. if (json == null || json == "")
  691. {
  692. json += @"{""THUAI6""" + ":" + @"""2023""}";
  693. }
  694. var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  695. if (dict == null || !dict.ContainsKey("download") || "false" == dict["download"])
  696. {
  697. return false;
  698. }
  699. else if (dict["download"] == "true")
  700. {
  701. return true;
  702. }
  703. else
  704. {
  705. return false;
  706. }
  707. }
  708. }
  709. public static void DownloadAll() // 下载全部文件
  710. {
  711. string jsonName = "hash.json";
  712. string json;
  713. Tencent_cos_download Downloader = new Tencent_cos_download();
  714. try
  715. {
  716. // 如果json存在就删了重新下
  717. if (File.Exists(System.IO.Path.Combine(Data.FilePath, jsonName)))
  718. {
  719. File.Delete(System.IO.Path.Combine(Data.FilePath, jsonName));
  720. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  721. }
  722. else
  723. {
  724. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  725. }
  726. }
  727. catch (CosClientException clientEx)
  728. {
  729. // 请求失败
  730. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  731. return;
  732. }
  733. catch (CosServerException serverEx)
  734. {
  735. // 请求失败
  736. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  737. return;
  738. }
  739. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, jsonName)))
  740. json = r.ReadToEnd();
  741. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  742. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  743. newFileName.Clear();
  744. updateFileName.Clear();
  745. newFileName.Add("THUAI6.tar.gz");
  746. Download();
  747. Stream inStream = null;
  748. Stream gzipStream = null;
  749. TarArchive tarArchive = null;
  750. try
  751. {
  752. using (inStream = File.OpenRead(System.IO.Path.Combine(Data.FilePath, "THUAI6.tar.gz")))
  753. {
  754. using (gzipStream = new GZipInputStream(inStream))
  755. {
  756. tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
  757. tarArchive.ExtractContents(Data.FilePath);
  758. tarArchive.Close();
  759. }
  760. }
  761. }
  762. catch (Exception ex)
  763. {
  764. //出错
  765. }
  766. finally
  767. {
  768. if (null != tarArchive) tarArchive.Close();
  769. if (null != gzipStream) gzipStream.Close();
  770. if (null != inStream) inStream.Close();
  771. }
  772. FileInfo fileInfo = new FileInfo(System.IO.Path.Combine(Data.FilePath, "THUAI6.tar.gz"));
  773. fileInfo.Delete();
  774. string json2;
  775. Dictionary<string, string> dict = new Dictionary<string, string>();
  776. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  777. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  778. using (StreamReader r = new StreamReader(fs))
  779. {
  780. json2 = r.ReadToEnd();
  781. if (json2 == null || json2 == "")
  782. {
  783. json2 += @"{""THUAI6""" + ":" + @"""2023""}";
  784. }
  785. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json2);
  786. if (dict == null || !dict.ContainsKey("download"))
  787. {
  788. dict?.Add("download", "true");
  789. }
  790. else
  791. {
  792. dict["download"] = "true";
  793. }
  794. }
  795. using FileStream fs2 = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  796. using StreamWriter sw = new StreamWriter(fs2);
  797. fs2.SetLength(0);
  798. sw.Write(JsonConvert.SerializeObject(dict));
  799. Check();
  800. Download();
  801. if (File.Exists(Data.FilePath + "/THUAI6/AI.cpp"))
  802. {
  803. FileInfo userCpp = new FileInfo((Data.FilePath + "/THUAI6/AI.cpp").Replace("/", "\\"));
  804. userCpp.MoveTo(Data.FilePath + "/THUAI6/win/CAPI/cpp/API/src/AI.cpp", true);
  805. }
  806. if (File.Exists(Data.FilePath + "/THUAI6/AI.py"))
  807. {
  808. FileInfo userCpp = new FileInfo((Data.FilePath + "/THUAI6/AI.py").Replace("/", "\\"));
  809. userCpp.MoveTo(Data.FilePath + "/THUAI6/win/CAPI/python/PyAPI/AI.cpp", true);
  810. }
  811. }
  812. public static void Change_all_hash(string topDir, Dictionary<string, string> jsonDict) // 更改HASH
  813. {
  814. DirectoryInfo theFolder = new DirectoryInfo(@topDir);
  815. bool ifexist = false;
  816. // 遍历文件
  817. foreach (FileInfo NextFile in theFolder.GetFiles())
  818. {
  819. string filepath = topDir + @"/" + NextFile.Name; // 文件路径
  820. //Console.WriteLine(filepath);
  821. foreach (KeyValuePair<string, string> pair in jsonDict)
  822. {
  823. if (System.IO.Path.Equals(filepath, System.IO.Path.Combine(Data.FilePath, pair.Key).Replace('\\', '/')))
  824. {
  825. ifexist = true;
  826. string MD5 = GetFileMd5Hash(filepath);
  827. jsonDict[pair.Key] = MD5;
  828. }
  829. }
  830. if (!ifexist && NextFile.Name != "hash.json")
  831. {
  832. string MD5 = GetFileMd5Hash(filepath);
  833. string relapath = filepath.Replace(Data.FilePath + '/', string.Empty);
  834. jsonDict.Add(relapath, MD5);
  835. }
  836. ifexist = false;
  837. }
  838. // 遍历文件夹
  839. foreach (DirectoryInfo NextFolder in theFolder.GetDirectories())
  840. {
  841. if (System.IO.Path.Equals(NextFolder.FullName, System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder))))
  842. {
  843. foreach (FileInfo NextFile in NextFolder.GetFiles())
  844. {
  845. if (NextFile.Name == "AI.cpp" || NextFile.Name == "AI.py")
  846. {
  847. string MD5 = GetFileMd5Hash(NextFile.FullName);
  848. string relapath = NextFile.FullName.Replace('\\', '/').Replace(Data.FilePath + '/', string.Empty);
  849. jsonDict.Add(relapath, MD5);
  850. }
  851. }
  852. continue; // 如果是选手文件夹就忽略
  853. }
  854. Change_all_hash(NextFolder.FullName.Replace('\\', '/'), jsonDict);
  855. }
  856. }
  857. public static void UpdateHash()
  858. {
  859. while (true)
  860. {
  861. if (Directory.Exists(Data.FilePath))
  862. {
  863. string json;
  864. if (!File.Exists(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  865. {
  866. Console.WriteLine("hash.json文件丢失!即将重新下载该文件!");
  867. GetNewHash();
  868. }
  869. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  870. json = r.ReadToEnd();
  871. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("/", @"\\");
  872. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  873. Change_all_hash(Data.FilePath, jsonDict);
  874. OverwriteHash(jsonDict);
  875. break;
  876. }
  877. else
  878. {
  879. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  880. Data.ResetFilepath(Console.ReadLine());
  881. }
  882. }
  883. }
  884. public static int DeleteAll()
  885. {
  886. DirectoryInfo di = new DirectoryInfo(Data.FilePath + "/THUAI6");
  887. //DirectoryInfo player = new DirectoryInfo(System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder)));
  888. FileInfo[] allfile = di.GetFiles();
  889. try
  890. {
  891. foreach (FileInfo file in allfile)
  892. {
  893. //if(file.Name == "AI.cpp" || file.Name == "AI.py")
  894. //{
  895. // string filename = System.IO.Path.GetFileName(file.FullName);
  896. // file.MoveTo(System.IO.Path.Combine(Data.FilePath, filename));
  897. // continue;
  898. //}
  899. file.Delete();
  900. }
  901. FileInfo userFileCpp = new FileInfo(Data.FilePath + "/THUAI6/win/CAPI/cpp/API/src/AI.cpp");
  902. FileInfo userFilePy = new FileInfo(Data.FilePath + "/THUAI6/win/CAPI/python/PyAPI/AI.py");
  903. userFileCpp.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", System.IO.Path.GetFileName(userFileCpp.FullName)));
  904. userFilePy.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", System.IO.Path.GetFileName(userFilePy.FullName)));
  905. foreach (DirectoryInfo subdi in di.GetDirectories())
  906. {
  907. subdi.Delete(true);
  908. }
  909. FileInfo hashFile = new FileInfo(Data.FilePath + "/hash.json");
  910. hashFile.Delete();
  911. }
  912. catch (UnauthorizedAccessException)
  913. {
  914. Console.WriteLine("权限不足,无法删除!");
  915. return -2;
  916. }
  917. catch (DirectoryNotFoundException)
  918. {
  919. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  920. return -3;
  921. }
  922. catch (IOException)
  923. {
  924. Console.WriteLine("文件已经打开,请关闭后再删除");
  925. return -1;
  926. }
  927. string json2;
  928. Dictionary<string, string> dict = new Dictionary<string, string>();
  929. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  930. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  931. using (StreamReader r = new StreamReader(fs))
  932. {
  933. json2 = r.ReadToEnd();
  934. if (json2 == null || json2 == "")
  935. {
  936. json2 += @"{""THUAI6""" + ":" + @"""2023""}";
  937. }
  938. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json2);
  939. if (dict == null || !dict.ContainsKey("download"))
  940. {
  941. dict?.Add("download", "false");
  942. }
  943. else
  944. {
  945. dict["download"] = "false";
  946. }
  947. }
  948. using FileStream fs2 = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  949. using StreamWriter sw = new StreamWriter(fs2);
  950. fs2.SetLength(0);
  951. sw.Write(JsonConvert.SerializeObject(dict));
  952. sw.Close();
  953. fs2.Close();
  954. try
  955. {
  956. File.Delete(Data.path);
  957. }
  958. catch (UnauthorizedAccessException)
  959. {
  960. Console.WriteLine("权限不足,无法删除!");
  961. return -2;
  962. }
  963. catch (DirectoryNotFoundException)
  964. {
  965. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  966. return -3;
  967. }
  968. catch (IOException)
  969. {
  970. Console.WriteLine("文件已经打开,请关闭后再删除");
  971. return -1;
  972. }
  973. return 0;
  974. }
  975. public static void OverwriteHash(Dictionary<string, string> jsonDict)
  976. {
  977. string Contentjson = JsonConvert.SerializeObject(jsonDict);
  978. Contentjson = Contentjson.Replace("\r", String.Empty).Replace("\n", String.Empty).Replace(@"\\", "/");
  979. File.WriteAllText(@System.IO.Path.Combine(Data.FilePath, "hash.json"), Contentjson);
  980. }
  981. public static int MoveProgram(string newPath)
  982. {
  983. DirectoryInfo newdi = new DirectoryInfo(newPath + "/THUAI6");
  984. DirectoryInfo olddi = new DirectoryInfo(Data.FilePath + "/THUAI6");
  985. try
  986. {
  987. if (!Directory.Exists(newPath + "/THUAI6"))
  988. Directory.CreateDirectory(newPath + "/THUAI6");
  989. foreach (DirectoryInfo direct in olddi.GetDirectories())
  990. {
  991. direct.MoveTo(System.IO.Path.Combine(newPath + "/THUAI6", direct.Name));
  992. }
  993. foreach (FileInfo file in olddi.GetFiles())
  994. {
  995. file.MoveTo(System.IO.Path.Combine(newPath + "/THUAI6", file.Name));
  996. }
  997. olddi.Delete();
  998. }
  999. catch (DirectoryNotFoundException)
  1000. {
  1001. Console.WriteLine("原路径未找到!请检查文件是否损坏");
  1002. if (newdi.GetDirectories().Length != 0)
  1003. {
  1004. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  1005. {
  1006. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", newdirect.Name));
  1007. }
  1008. }
  1009. if (newdi.GetFiles().Length != 0)
  1010. {
  1011. foreach (FileInfo file in newdi.GetFiles())
  1012. {
  1013. file.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", file.Name));
  1014. }
  1015. }
  1016. Console.WriteLine("移动失败!");
  1017. if (newdi.Exists)
  1018. newdi.Delete();
  1019. return -2;
  1020. }
  1021. catch (IOException)
  1022. {
  1023. Console.WriteLine("文件已打开或者目标路径下有同名文件!");
  1024. if (newdi.GetDirectories().Length != 0)
  1025. {
  1026. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  1027. {
  1028. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", newdirect.Name));
  1029. }
  1030. }
  1031. if (newdi.GetFiles().Length != 0)
  1032. {
  1033. foreach (FileInfo file in newdi.GetFiles())
  1034. {
  1035. file.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", file.Name));
  1036. }
  1037. }
  1038. if (newdi.Exists)
  1039. newdi.Delete();
  1040. Console.WriteLine("移动失败!");
  1041. return -1;
  1042. }
  1043. FileInfo hashFile = new FileInfo(Data.FilePath + "/hash.json");
  1044. hashFile.MoveTo(newPath + "/hash.json");
  1045. Data.ResetFilepath(newPath);
  1046. Console.WriteLine("更改路径成功!");
  1047. return 0;
  1048. }
  1049. public static async Task main(string[] args)
  1050. {
  1051. var client = new HttpClient();
  1052. var web = new WebConnect.Web();
  1053. Data date = new Data("");
  1054. while (true)
  1055. {
  1056. Console.WriteLine($"1. 更新hash.json 2. 检查更新 3.下载{ProgramName} 4.删除{ProgramName} 5.启动进程 6.移动{ProgramName}到其它路径");
  1057. string choose = Console.ReadLine();
  1058. if (choose == "1")
  1059. {
  1060. if (!CheckAlreadyDownload())
  1061. {
  1062. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  1063. continue;
  1064. }
  1065. UpdateHash();
  1066. }
  1067. else if (choose == "2")
  1068. {
  1069. if (!CheckAlreadyDownload())
  1070. {
  1071. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  1072. continue;
  1073. }
  1074. while (true)
  1075. {
  1076. if (Data.FilePath != null && Directory.Exists(Data.FilePath))
  1077. {
  1078. Check();
  1079. break;
  1080. }
  1081. else
  1082. {
  1083. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  1084. Data.ResetFilepath(Console.ReadLine());
  1085. }
  1086. }
  1087. }
  1088. else if (choose == "3")
  1089. {
  1090. if (CheckAlreadyDownload())
  1091. {
  1092. Console.WriteLine($"已经将{ProgramName}下载到{Data.FilePath}!若要重新下载请先完成删除操作!");
  1093. }
  1094. else
  1095. {
  1096. string newpath;
  1097. Console.WriteLine("请输入下载路径:");
  1098. newpath = Console.ReadLine();
  1099. Data.ResetFilepath(newpath);
  1100. DownloadAll();
  1101. }
  1102. }
  1103. else if (choose == "4")
  1104. {
  1105. DeleteAll();
  1106. }
  1107. else if (choose == "5")
  1108. {
  1109. if (CheckAlreadyDownload())
  1110. {
  1111. Process.Start(System.IO.Path.Combine(Data.FilePath, startName));
  1112. }
  1113. else
  1114. {
  1115. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  1116. }
  1117. }
  1118. else if (choose == "6")
  1119. {
  1120. string newPath;
  1121. newPath = Console.ReadLine();
  1122. MoveProgram(newPath);
  1123. }
  1124. else if (choose == "7")
  1125. {
  1126. Console.WriteLine("请输入email:");
  1127. string username = Console.ReadLine();
  1128. Console.WriteLine("请输入密码:");
  1129. string password = Console.ReadLine();
  1130. await web.LoginToEEsast(client, username, password);
  1131. }
  1132. else if (choose == "8")
  1133. {
  1134. await web.UserDetails(client);
  1135. }
  1136. else if (choose == "9")
  1137. {
  1138. await web.UploadFiles(client, "", "", "");
  1139. }
  1140. else if (choose == "exit")
  1141. {
  1142. return;
  1143. }
  1144. }
  1145. }
  1146. public static int CheckSelfVersion()
  1147. {
  1148. Tencent_cos_download downloader = new Tencent_cos_download();
  1149. string hashName = "installerHash.json";
  1150. string dir = Directory.GetCurrentDirectory();
  1151. try
  1152. {
  1153. if (File.Exists(System.IO.Path.Combine(dir, hashName)))
  1154. File.Delete(System.IO.Path.Combine(dir, hashName));
  1155. downloader.download(System.IO.Path.Combine(dir, hashName), hashName);
  1156. }
  1157. catch
  1158. {
  1159. return -1;
  1160. }
  1161. string json;
  1162. using (StreamReader r = new StreamReader(System.IO.Path.Combine(dir, hashName)))
  1163. json = r.ReadToEnd();
  1164. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  1165. Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1166. if (jsonDict != null)
  1167. {
  1168. if (jsonDict.ContainsKey("InstallerUpdater.exe"))
  1169. {
  1170. string updaterHash = GetFileMd5Hash(System.IO.Path.Combine(dir, "InstallerUpdater.exe"));
  1171. if (updaterHash != null && !jsonDict["InstallerUpdater.exe"].Equals(updaterHash))
  1172. downloader.download(System.IO.Path.Combine(dir, "InstallerUpdater.exe"), "InstallerUpdater.exe");
  1173. }
  1174. else
  1175. return -1;
  1176. if (jsonDict.ContainsKey("Installer.exe"))
  1177. {
  1178. string selfHash = GetFileMd5Hash(System.IO.Path.Combine(dir, "Installer.exe"));
  1179. if (selfHash != null && !jsonDict["Installer.exe"].Equals(selfHash))
  1180. return 1;
  1181. }
  1182. else
  1183. return -1;
  1184. }
  1185. else
  1186. return -1;
  1187. return 0;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. namespace WebConnect
  1193. {
  1194. class Web
  1195. {
  1196. public enum language { cpp, py };
  1197. public static string logintoken = "";
  1198. async public Task<int> LoginToEEsast(HttpClient client, string useremail, string password)
  1199. {
  1200. string token = "";
  1201. try
  1202. {
  1203. using (var response = await client.PostAsync("https://api.eesast.com/users/login", JsonContent.Create(new
  1204. {
  1205. email = useremail,
  1206. password = password,
  1207. })))
  1208. {
  1209. switch (response.StatusCode)
  1210. {
  1211. case System.Net.HttpStatusCode.OK:
  1212. //Console.WriteLine("Success login");
  1213. token = (System.Text.Json.JsonSerializer.Deserialize(await response.Content.ReadAsStreamAsync(), typeof(LoginResponse), new JsonSerializerOptions()
  1214. {
  1215. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  1216. }) as LoginResponse)
  1217. ?.Token ??
  1218. throw new Exception("no token!");
  1219. logintoken = token;
  1220. SaveToken();
  1221. var info = JsonConvert.DeserializeObject<Dictionary<string, string>>(await response.Content.ReadAsStringAsync());
  1222. Downloader.UserInfo._id = info["_id"];
  1223. Downloader.UserInfo.email = info["email"];
  1224. break;
  1225. default:
  1226. int code = ((int)response.StatusCode);
  1227. //Console.WriteLine(code);
  1228. if (code == 401)
  1229. {
  1230. //Console.WriteLine("邮箱或密码错误!");
  1231. return -1;
  1232. }
  1233. break;
  1234. }
  1235. return 0;
  1236. }
  1237. }
  1238. catch
  1239. {
  1240. return -2;
  1241. }
  1242. }
  1243. /// <summary>
  1244. ///
  1245. /// </summary>
  1246. /// <param name="client">http client</param>
  1247. /// <param name="tarfile">代码源位置</param>
  1248. /// <param name="type">编程语言,格式为"cpp"或"python"</param>
  1249. /// <param name="plr">第x位玩家,格式为"player_x"</param>
  1250. /// <returns>-1:tokenFail;-2:FileNotExist;-3:CosFail;-4:loginTimeout;-5:Fail;-6:ReadFileFail;-7:networkError</returns>
  1251. async public Task<int> UploadFiles(HttpClient client, string tarfile, string type, string plr) //用来上传文件
  1252. {
  1253. if (!ReadToken()) //读取token失败
  1254. {
  1255. return -1;
  1256. }
  1257. try
  1258. {
  1259. string content;
  1260. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1261. if (!File.Exists(tarfile))
  1262. {
  1263. //Console.WriteLine("文件不存在!");
  1264. return -2;
  1265. }
  1266. using FileStream fs = new FileStream(tarfile, FileMode.Open, FileAccess.Read);
  1267. using StreamReader sr = new StreamReader(fs);
  1268. content = sr.ReadToEnd();
  1269. string targetUrl = $"https://api.eesast.com/static/player?team_id={await GetTeamId()}";
  1270. using (var response = await client.GetAsync(targetUrl))
  1271. {
  1272. switch (response.StatusCode)
  1273. {
  1274. case System.Net.HttpStatusCode.OK:
  1275. var res = JsonConvert.DeserializeObject<Dictionary<string, string>>(await response.Content.ReadAsStringAsync());
  1276. string appid = "1255334966"; // 设置腾讯云账户的账户标识(APPID)
  1277. string region = "ap-beijing"; // 设置一个默认的存储桶地域
  1278. CosXmlConfig config = new CosXmlConfig.Builder()
  1279. .IsHttps(true) // 设置默认 HTTPS 请求
  1280. .SetAppid(appid) // 设置腾讯云账户的账户标识 APPID
  1281. .SetRegion(region) // 设置一个默认的存储桶地域
  1282. .SetDebugLog(true) // 显示日志
  1283. .Build(); // 创建 CosXmlConfig 对象
  1284. string tmpSecretId = res["TmpSecretId"]; //"临时密钥 SecretId";
  1285. string tmpSecretKey = res["TmpSecretKey"]; //"临时密钥 SecretKey";
  1286. string tmpToken = res["SecurityToken"]; //"临时密钥 token";
  1287. long tmpExpiredTime = Convert.ToInt64(res["ExpiredTime"]);//临时密钥有效截止时间,精确到秒
  1288. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  1289. tmpSecretId, tmpSecretKey, tmpExpiredTime, tmpToken
  1290. );
  1291. // 初始化 CosXmlServer
  1292. CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);
  1293. // 初始化 TransferConfig
  1294. TransferConfig transferConfig = new TransferConfig();
  1295. // 初始化 TransferManager
  1296. TransferManager transferManager = new TransferManager(cosXml, transferConfig);
  1297. string bucket = "eesast-1255334966"; //存储桶,格式:BucketName-APPID
  1298. string cosPath = $"/THUAI6/{GetTeamId()}/{type}/{plr}"; //对象在存储桶中的位置标识符,即称对象键
  1299. string srcPath = tarfile;//本地文件绝对路径
  1300. // 上传对象
  1301. COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);
  1302. uploadTask.SetSrcPath(srcPath);
  1303. uploadTask.progressCallback = delegate (long completed, long total)
  1304. {
  1305. //Console.WriteLine(string.Format("progress = {0:##.##}%", completed * 100.0 / total));
  1306. };
  1307. try
  1308. {
  1309. COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask);
  1310. //Console.WriteLine(result.GetResultInfo());
  1311. string eTag = result.eTag;
  1312. //到这里应该是成功了,但是因为我没有试过,也不知道具体情况,可能还要根据result的内容判断
  1313. }
  1314. catch (Exception)
  1315. {
  1316. return -3;
  1317. }
  1318. break;
  1319. case System.Net.HttpStatusCode.Unauthorized:
  1320. //Console.WriteLine("您未登录或登录过期,请先登录");
  1321. return -4;
  1322. default:
  1323. //Console.WriteLine("上传失败!");
  1324. return -5;
  1325. }
  1326. }
  1327. }
  1328. catch (IOException)
  1329. {
  1330. //Console.WriteLine("文件读取错误!请检查文件是否被其它应用占用!");
  1331. return -6;
  1332. }
  1333. catch
  1334. {
  1335. //Console.WriteLine("请求错误!请检查网络连接!");
  1336. return -7;
  1337. }
  1338. return 0;
  1339. }
  1340. async public Task UserDetails(HttpClient client) // 用来测试访问网站
  1341. {
  1342. if (!ReadToken()) // 读取token失败
  1343. {
  1344. return;
  1345. }
  1346. try
  1347. {
  1348. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1349. Console.WriteLine(logintoken);
  1350. using (var response = await client.GetAsync("https://api.eesast.com/application/info")) // JsonContent.Create(new
  1351. //{
  1352. //})))
  1353. {
  1354. switch (response.StatusCode)
  1355. {
  1356. case System.Net.HttpStatusCode.OK:
  1357. Console.WriteLine("Require OK");
  1358. Console.WriteLine(await response.Content.ReadAsStringAsync());
  1359. break;
  1360. default:
  1361. int code = ((int)response.StatusCode);
  1362. if (code == 401)
  1363. {
  1364. Console.WriteLine("您未登录或登录过期,请先登录");
  1365. }
  1366. return;
  1367. }
  1368. }
  1369. }
  1370. catch
  1371. {
  1372. Console.WriteLine("请求错误!请检查网络连接!");
  1373. }
  1374. }
  1375. public void SaveToken() // 保存token
  1376. {
  1377. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1378. try
  1379. {
  1380. string json;
  1381. Dictionary<string, string> dict = new Dictionary<string, string>();
  1382. using FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1383. using (StreamReader r = new StreamReader(fs))
  1384. {
  1385. json = r.ReadToEnd();
  1386. if (json == null || json == "")
  1387. {
  1388. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1389. }
  1390. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1391. if (dict.ContainsKey("token"))
  1392. {
  1393. dict.Remove("token");
  1394. }
  1395. dict?.Add("token", logintoken);
  1396. }
  1397. using FileStream fs2 = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1398. using StreamWriter sw = new StreamWriter(fs2);
  1399. fs2.SetLength(0);
  1400. sw.Write(JsonConvert.SerializeObject(dict)); //将token写入文件
  1401. }
  1402. catch (DirectoryNotFoundException)
  1403. {
  1404. Console.WriteLine("保存token时未找到下载器地址!请检查下载器是否被移动!");
  1405. }
  1406. catch (PathTooLongException)
  1407. {
  1408. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1409. }
  1410. catch (ArgumentNullException)
  1411. {
  1412. Console.WriteLine("下载器路径初始化失败!");
  1413. }
  1414. catch (IOException)
  1415. {
  1416. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  1417. }
  1418. }
  1419. public static int WriteUserEmail(string email)
  1420. {
  1421. try
  1422. {
  1423. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1424. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  1425. StreamReader sr = new StreamReader(fs);
  1426. string json = sr.ReadToEnd();
  1427. if (json == null || json == "")
  1428. {
  1429. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1430. }
  1431. Dictionary<string, string> dict = new Dictionary<string, string>();
  1432. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1433. if (!dict.ContainsKey("email"))
  1434. {
  1435. dict.Add("email", email);
  1436. }
  1437. else
  1438. {
  1439. dict["email"] = email;
  1440. }
  1441. sr.Close();
  1442. fs.Close();
  1443. FileStream fs2 = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  1444. StreamWriter sw = new StreamWriter(fs2);
  1445. sw.WriteLine(JsonConvert.SerializeObject(dict));
  1446. sw.Close();
  1447. fs2.Close();
  1448. return 0;//成功
  1449. }
  1450. catch
  1451. {
  1452. return -1;//失败
  1453. }
  1454. }
  1455. public static int WriteUserPassword(string password)
  1456. {
  1457. try
  1458. {
  1459. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1460. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  1461. StreamReader sr = new StreamReader(fs);
  1462. string json = sr.ReadToEnd();
  1463. if (json == null || json == "")
  1464. {
  1465. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1466. }
  1467. Dictionary<string, string> dict = new Dictionary<string, string>();
  1468. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1469. if (!dict.ContainsKey("password"))
  1470. {
  1471. dict.Add("password", password);
  1472. }
  1473. else
  1474. {
  1475. dict["password"] = password;
  1476. }
  1477. sr.Close();
  1478. fs.Close();
  1479. FileStream fs2 = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  1480. StreamWriter sw = new StreamWriter(fs2);
  1481. sw.WriteLine(JsonConvert.SerializeObject(dict));
  1482. sw.Close();
  1483. fs2.Close();
  1484. return 0;//成功
  1485. }
  1486. catch
  1487. {
  1488. return -1;//失败,THUAI6.json 文件不存在或者已被占用
  1489. }
  1490. }
  1491. public static string ReadUserPassword()
  1492. {
  1493. try
  1494. {
  1495. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1496. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  1497. StreamReader sr = new StreamReader(fs);
  1498. string json = sr.ReadToEnd();
  1499. Dictionary<string, string> dict = new Dictionary<string, string>();
  1500. if (json == null || json == "")
  1501. {
  1502. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1503. }
  1504. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1505. return dict["password"];
  1506. }
  1507. catch
  1508. {
  1509. return null; //文件不存在或者已被占用
  1510. }
  1511. }
  1512. public static string ReadUserEmail()
  1513. {
  1514. try
  1515. {
  1516. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1517. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  1518. StreamReader sr = new StreamReader(fs);
  1519. string json = sr.ReadToEnd();
  1520. Dictionary<string, string> dict = new Dictionary<string, string>();
  1521. if (json == null || json == "")
  1522. {
  1523. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1524. }
  1525. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1526. return dict["email"];
  1527. }
  1528. catch
  1529. {
  1530. return null;
  1531. }
  1532. }
  1533. public bool ReadToken() // 读取token
  1534. {
  1535. try
  1536. {
  1537. string json;
  1538. Dictionary<string, string> dict = new Dictionary<string, string>();
  1539. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1540. using FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  1541. using StreamReader sr = new StreamReader(fs);
  1542. json = sr.ReadToEnd();
  1543. if (json == null || json == "")
  1544. {
  1545. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1546. }
  1547. dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1548. if (!dict.ContainsKey("token"))
  1549. {
  1550. return false;
  1551. }
  1552. else
  1553. {
  1554. logintoken = dict["token"];
  1555. return true;
  1556. }
  1557. }
  1558. catch (DirectoryNotFoundException)
  1559. {
  1560. Console.WriteLine("读取token时未找到下载器地址!请检查下载器是否被移动!");
  1561. return false;
  1562. }
  1563. catch (FileNotFoundException)
  1564. {
  1565. //没有登陆
  1566. Console.WriteLine("请先登录!");
  1567. return false;
  1568. }
  1569. catch (PathTooLongException)
  1570. {
  1571. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1572. return false;
  1573. }
  1574. catch (ArgumentNullException)
  1575. {
  1576. Console.WriteLine("下载器路径初始化失败!");
  1577. return false;
  1578. }
  1579. catch (IOException)
  1580. {
  1581. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  1582. return false;
  1583. }
  1584. }
  1585. async public Task<string> GetTeamId()
  1586. {
  1587. var client = new HttpClient();
  1588. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  1589. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  1590. //var content = new StringContent($@"
  1591. // {{
  1592. // ""query"": ""query MyQuery {{contest_team_member(where: {{user_id: {{_eq: \""{Downloader.UserInfo._id}\""}}}}) {{ team_id }}}}"",
  1593. // ""variables"": {{}},
  1594. // }}", null, "application/json");
  1595. 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");
  1596. request.Content = content;
  1597. var response = await client.SendAsync(request);
  1598. response.EnsureSuccessStatusCode();
  1599. var info = await response.Content.ReadAsStringAsync();
  1600. var s1 = JsonConvert.DeserializeObject<Dictionary<string, object>>(info)["data"];
  1601. var s2 = JsonConvert.DeserializeObject<Dictionary<string, List<object>>>(s1.ToString())["contest_team_member"];
  1602. var sres = JsonConvert.DeserializeObject<Dictionary<string, string>>(s2[0].ToString())["team_id"];
  1603. return sres;
  1604. }
  1605. async public Task<string> GetUserId(string learnNumber)
  1606. {
  1607. var client = new HttpClient();
  1608. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  1609. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  1610. var content = new StringContent("{\"query\":\"query MyQuery {\r\n user(where: {id: {_eq: \""
  1611. + learnNumber + "\"}}) {\r\n _id\r\n }\r\n}\r\n\",\"variables\":{}}", null, "application/json");
  1612. request.Content = content;
  1613. var response = await client.SendAsync(request);
  1614. response.EnsureSuccessStatusCode();
  1615. return await response.Content.ReadAsStringAsync();
  1616. }
  1617. }
  1618. [Serializable]
  1619. record LoginResponse
  1620. {
  1621. // Map `Token` to `token` when serializing
  1622. public string Token { get; set; } = "";
  1623. }
  1624. }