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

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