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

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265
  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.Collections.Concurrent;
  24. //using System.Windows.Forms;
  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. using starter.viewmodel.settings;
  38. using System.Security.Permissions;
  39. using System.Windows.Media;
  40. namespace starter.viewmodel.settings
  41. {
  42. /// <summary>
  43. /// Settings Window Model
  44. /// </summary>
  45. public class SettingsModel
  46. {
  47. /// <summary>
  48. /// downloader function
  49. /// </summary>
  50. private Data configData = new Data("");
  51. private Tencent_cos_download cloud = new Tencent_cos_download();
  52. private HttpClient client = new HttpClient();
  53. private WebConnect.Web web = new WebConnect.Web();
  54. public SettingsModel()
  55. {
  56. Route = Data.FilePath;
  57. Username = "";
  58. Password = "";
  59. updates = "";
  60. CodeRoute = "";
  61. PlayerNum = "nSelect";
  62. UploadReady = false;
  63. LoginFailed = false;
  64. launchLanguage = LaunchLanguage.cpp;
  65. usingOS = ReadUsingOS();
  66. }
  67. /// <summary>
  68. /// save settings
  69. /// </summary>
  70. public bool install()
  71. {
  72. if (Tencent_cos_download.CheckAlreadyDownload())
  73. {
  74. MessageBoxResult repeatOption = MessageBox.Show($"文件已存在于{Downloader.Program.Data.FilePath},是否移动到新位置?", "重复安装", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
  75. // ask if abort install, with warning sign, defalut move instead of abort;
  76. if (repeatOption == MessageBoxResult.No)
  77. {
  78. Route = Data.FilePath;
  79. return false;
  80. }
  81. else
  82. {
  83. Downloader.Program.Tencent_cos_download.MoveProgram(Route);
  84. return true;
  85. }
  86. }
  87. else
  88. {
  89. Data.ResetFilepath(Route);
  90. Tencent_cos_download.DownloadAll();
  91. return true;
  92. }
  93. }
  94. public int move()
  95. {
  96. int state = Tencent_cos_download.MoveProgram(Route);
  97. if (state != 0)
  98. Route = Data.FilePath;
  99. return state;
  100. }
  101. ///<summary>
  102. ///check for update
  103. /// </summary>
  104. static bool ProfileAvailable
  105. {
  106. get; set;
  107. }
  108. /// <summary>
  109. /// 检查更新
  110. /// </summary>
  111. /// <returns></returns>
  112. public Status checkUpdate()
  113. {
  114. UpdateInfo updateInfo = Tencent_cos_download.Check(usingOS);
  115. if (updateInfo.newFileCount == -1)
  116. {
  117. if (updateInfo.changedFileCount == -1)
  118. {
  119. return Status.error;
  120. }
  121. else
  122. {
  123. return Status.disconnected;
  124. }
  125. }
  126. else
  127. {
  128. if (updateInfo.changedFileCount != 0 || updateInfo.newFileCount != 0)
  129. {
  130. Updates = $"{updateInfo.newFileCount}个新文件,{updateInfo.changedFileCount}个文件变化";
  131. }
  132. return Status.menu;
  133. }
  134. }
  135. public async Task<int> Login()
  136. {
  137. return await web.LoginToEEsast(client, Username, Password);
  138. }
  139. public bool RememberUser()
  140. {
  141. int result = 0;
  142. result |= Web.WriteJson("email", Username);
  143. result |= Web.WriteJson("password", Password);
  144. return result == 0;
  145. }
  146. public bool RecallUser()
  147. {
  148. var username = Web.ReadJson("email");
  149. if (username == null || username.Equals(""))
  150. {
  151. Username = "";
  152. return false;
  153. }
  154. Username = username;
  155. var password = Web.ReadJson("password");
  156. if (password == null || password.Equals(""))
  157. {
  158. Password = "";
  159. return false;
  160. }
  161. Password = password;
  162. return true;
  163. }
  164. public bool ForgetUser()
  165. {
  166. int result = 0;
  167. result |= Web.WriteJson("email", "");
  168. result |= Web.WriteJson("password", "");
  169. return result == 0;
  170. }
  171. public bool Update()
  172. {
  173. try
  174. {
  175. return Tencent_cos_download.Update();
  176. }
  177. catch
  178. {
  179. return false;
  180. }
  181. }
  182. public int Uninst()
  183. {
  184. return Tencent_cos_download.DeleteAll();
  185. }
  186. public bool Launch()
  187. {
  188. if (Tencent_cos_download.CheckAlreadyDownload())
  189. {
  190. //Process.Start(System.IO.Path.Combine(Data.FilePath, startName));
  191. switch (RunProgram.RunInfo.mode)
  192. {
  193. case RunProgram.RunMode.ServerOnly:
  194. RunProgram.StartServer(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  195. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  196. break;
  197. case RunProgram.RunMode.ServerForDebugOnly:
  198. RunProgram.StartServerForDebug(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  199. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  200. break;
  201. case RunProgram.RunMode.GUIAttendGameOnly:
  202. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.characterID,
  203. false, RunProgram.RunInfo.occupation, RunProgram.RunInfo.type);
  204. break;
  205. case RunProgram.RunMode.GUIVisit:
  206. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, 0, true, 1, 1);
  207. break;
  208. case RunProgram.RunMode.GUIAndAICpp:
  209. RunProgram.StartServerForDebug(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  210. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  211. Task.Delay(100);
  212. RunProgram.RunCpp(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  213. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  214. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  215. RunProgram.RunInfo.playerId = null;
  216. RunProgram.RunInfo.filePath = null;
  217. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.characterID,
  218. false, RunProgram.RunInfo.occupation, RunProgram.RunInfo.type);
  219. break;
  220. case RunProgram.RunMode.GUIAndAIPython:
  221. RunProgram.StartServerForDebug(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  222. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  223. Task.Delay(100);
  224. RunProgram.RunPython(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  225. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  226. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  227. RunProgram.RunInfo.playerId = null;
  228. RunProgram.RunInfo.filePath = null;
  229. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.characterID,
  230. false, RunProgram.RunInfo.occupation, RunProgram.RunInfo.type);
  231. break;
  232. case RunProgram.RunMode.ServerAndCpp:
  233. RunProgram.StartServer(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  234. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  235. Task.Delay(100);
  236. RunProgram.RunCpp(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  237. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  238. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  239. RunProgram.RunInfo.playerId = null;
  240. RunProgram.RunInfo.filePath = null;
  241. break;
  242. case RunProgram.RunMode.ServerAndPython:
  243. RunProgram.StartServer(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  244. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  245. Task.Delay(100);
  246. RunProgram.RunPython(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  247. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  248. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  249. RunProgram.RunInfo.playerId = null;
  250. RunProgram.RunInfo.filePath = null;
  251. break;
  252. case RunProgram.RunMode.ServerAndCppVisit:
  253. RunProgram.StartServer(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  254. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  255. Task.Delay(100);
  256. RunProgram.RunCpp(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  257. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  258. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  259. RunProgram.RunInfo.playerId = null;
  260. RunProgram.RunInfo.filePath = null;
  261. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.characterID, true, 0, 1);
  262. break;
  263. case RunProgram.RunMode.ServerAndPythonVisit:
  264. RunProgram.StartServer(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  265. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  266. Task.Delay(100);
  267. RunProgram.RunPython(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  268. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  269. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  270. RunProgram.RunInfo.playerId = null;
  271. RunProgram.RunInfo.filePath = null;
  272. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.characterID, true, 0, 1);
  273. break;
  274. case RunProgram.RunMode.ServerDebugAndCppVisit:
  275. RunProgram.StartServerForDebug(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  276. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  277. Task.Delay(100);
  278. RunProgram.RunCpp(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  279. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  280. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  281. RunProgram.RunInfo.playerId = null;
  282. RunProgram.RunInfo.filePath = null;
  283. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.characterID, true, 0, 1);
  284. break;
  285. case RunProgram.RunMode.ServerDebugAndPythonVisit:
  286. RunProgram.StartServerForDebug(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  287. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.gameTimeSec, RunProgram.RunInfo.playbackFileName);
  288. Task.Delay(100);
  289. RunProgram.RunPython(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.studentCount,
  290. RunProgram.RunInfo.trickerCount, RunProgram.RunInfo.saveDebugLog, RunProgram.RunInfo.showDebugLog,
  291. RunProgram.RunInfo.warningOnly, RunProgram.RunInfo.playerId, RunProgram.RunInfo.filePath);
  292. RunProgram.RunInfo.playerId = null;
  293. RunProgram.RunInfo.filePath = null;
  294. RunProgram.RunGUIClient(RunProgram.RunInfo.IP, RunProgram.RunInfo.port, RunProgram.RunInfo.characterID, true, 0, 1);
  295. break;
  296. }
  297. return true;
  298. }
  299. else
  300. {
  301. MessageBox.Show($"文件还不存在,请安装主体文件", "文件不存在", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
  302. return false;
  303. }
  304. }
  305. public async Task<int> Upload()
  306. {
  307. switch (CodeRoute.Substring(CodeRoute.LastIndexOf('.') + 1))
  308. {
  309. case "cpp":
  310. case "h":
  311. Language = "cpp";
  312. break;
  313. case "py":
  314. Language = "python";
  315. break;
  316. default:
  317. return -8;
  318. }
  319. if (PlayerNum.Equals("nSelect"))
  320. return -9;
  321. return await web.UploadFiles(client, CodeRoute, Language, PlayerNum);
  322. }
  323. public bool WriteUsingOS()
  324. {
  325. string OS = "";
  326. switch (usingOS)
  327. {
  328. case UsingOS.Win:
  329. OS = "win";
  330. break;
  331. case UsingOS.Linux:
  332. OS = "linux";
  333. break;
  334. case UsingOS.OSX:
  335. OS = "osx";
  336. break;
  337. }
  338. return Web.WriteJson("OS", OS) == 0;
  339. }
  340. public UsingOS ReadUsingOS()
  341. {
  342. return Web.ReadJson("OS") switch
  343. {
  344. "linux" => UsingOS.Linux,
  345. "osx" => UsingOS.OSX,
  346. _ => UsingOS.Win,
  347. };
  348. }
  349. /// <summary>
  350. /// Route of files
  351. /// </summary>
  352. public string Route
  353. {
  354. get; set;
  355. }
  356. public string Username
  357. {
  358. get; set;
  359. }
  360. public string Password
  361. {
  362. get; set;
  363. }
  364. public string CodeRoute
  365. {
  366. get; set;
  367. }
  368. public string? Language
  369. {
  370. get; set;
  371. }
  372. public string PlayerNum
  373. {
  374. get; set;
  375. }
  376. /// <summary>
  377. /// 关于更新的屏幕显示信息
  378. /// </summary>
  379. private string updates;
  380. public string Updates
  381. {
  382. get
  383. {
  384. return updates;
  385. }
  386. set
  387. {
  388. updates = value;
  389. }
  390. }
  391. /// <summary>
  392. /// 关于介绍的屏幕显示信息
  393. /// </summary>
  394. public enum Status { newUser, menu, move, working, initializing, disconnected, error, successful, login, web, launch };
  395. public Status status
  396. {
  397. get; set;
  398. }
  399. public bool Working
  400. {
  401. get; set;
  402. }
  403. /// <summary>
  404. /// if an update is planned
  405. /// </summary>
  406. public bool UpdatePlanned
  407. {
  408. get
  409. {
  410. return Program.UpdatePlanned;
  411. }
  412. }
  413. public bool CombatCompleted
  414. {
  415. get
  416. {
  417. return false;
  418. }
  419. }
  420. public bool LoginFailed
  421. {
  422. get; set;
  423. }
  424. public bool UploadReady
  425. {
  426. get; set;
  427. }
  428. public bool RememberMe
  429. {
  430. get; set;
  431. }
  432. public enum LaunchLanguage { cpp, python };
  433. public LaunchLanguage launchLanguage
  434. {
  435. get; set;
  436. }
  437. public enum UsingOS { Win, Linux, OSX };
  438. public UsingOS usingOS
  439. {
  440. get; set;
  441. }
  442. }
  443. }
  444. namespace Downloader
  445. {
  446. class UserInfo
  447. {
  448. static public string _id = "";
  449. static public string email = "";
  450. }
  451. class Program
  452. {
  453. static ConcurrentQueue<string> newFileName = new ConcurrentQueue<string>();
  454. //static List<string> newFileName = new List<string>(); // 新文件名
  455. static ConcurrentQueue<string> updateFileName = new ConcurrentQueue<string>(); // 更新文件名
  456. static List<string> updateFailed = new List<string>(); //更新失败的文件名
  457. static public List<string> UpdateFailed
  458. {
  459. get { return updateFailed; }
  460. }
  461. static public void ResetUpdateFailedInfo()
  462. {
  463. updateFailed.Clear();
  464. }
  465. public static string ProgramName = "THUAI6"; // 要运行或下载的程序名称
  466. public static string playerFolder = "player"; // 选手代码保存文件夹路径
  467. public static string startName = "maintest.exe"; // 启动的程序名
  468. public struct UpdateInfo // 更新信息,包括新版本版本号、更改文件数和新文件数
  469. {
  470. public string status;
  471. public int changedFileCount;
  472. public int newFileCount;
  473. }
  474. public static bool UpdatePlanned
  475. {
  476. get; set;
  477. }
  478. static int filenum = 0; // 总文件个数
  479. public class Data
  480. {
  481. public static string path = ""; // 标记路径记录文件THUAI6.json的路径
  482. public static string FilePath = ""; // 最后一级为THUAI6文件夹所在目录
  483. public static string dataPath = ""; // C盘的文档文件夹
  484. public Data(string path)
  485. {
  486. dataPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  487. //dataPath = new DirectoryInfo(".").FullName;
  488. Data.path = System.IO.Path.Combine(dataPath, "THUAI6.json");
  489. if (File.Exists(Data.path))
  490. {
  491. Dictionary<string, string>? dict;
  492. using (StreamReader r = new StreamReader(Data.path))
  493. {
  494. string json = r.ReadToEnd();
  495. if (json == null || json == "")
  496. {
  497. json += @"{""THUAI6""" + ":" + @"""2023""}";
  498. }
  499. dict = Utils.TryDeserializeJson<Dictionary<string, string>>(json);
  500. if (dict != null && dict.ContainsKey("installpath"))
  501. {
  502. FilePath = dict["installpath"].Replace('\\', '/');
  503. } //读取安装路径
  504. }
  505. dict?.TryAdd("installpath", @path);
  506. using FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  507. using StreamWriter sw = new StreamWriter(fs);
  508. sw.Write(JsonConvert.SerializeObject(dict));
  509. sw.Flush();
  510. }
  511. else
  512. {
  513. FilePath = System.IO.Path.GetDirectoryName(@path)
  514. ?? throw new Exception("Failed to get the path of the file");
  515. //将dat文件写入程序运行路径
  516. string json;
  517. Dictionary<string, string>? dict;
  518. using FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  519. using (StreamReader r = new StreamReader(fs))
  520. {
  521. json = r.ReadToEnd();
  522. if (json == null || json == "")
  523. {
  524. json += @"{""THUAI6""" + ":" + @"""2023""}";
  525. }
  526. dict = Utils.TryDeserializeJson<Dictionary<string, string>>(json);
  527. dict?.Add("installpath", path);
  528. }
  529. using FileStream fs2 = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  530. using StreamWriter sw = new StreamWriter(fs2);
  531. sw.Write(JsonConvert.SerializeObject(dict));
  532. sw.Flush();
  533. }
  534. }
  535. public static void ResetFilepath(string newPath)
  536. {
  537. string json;
  538. Dictionary<string, string>? dict;
  539. FilePath = newPath.Replace('\\', '/');
  540. path = System.IO.Path.Combine(dataPath, "THUAI6.json");
  541. using FileStream fs = new FileStream(Data.path, FileMode.Create, FileAccess.ReadWrite);
  542. using (StreamReader r = new StreamReader(fs))
  543. {
  544. json = r.ReadToEnd();
  545. if (json == null || json == "")
  546. {
  547. json += @"{""THUAI6""" + ":" + @"""2023""}";
  548. }
  549. dict = Utils.TryDeserializeJson<Dictionary<string, string>>(json);
  550. if (dict != null && dict.ContainsKey("installpath"))
  551. {
  552. dict["installpath"] = newPath;
  553. }
  554. else
  555. {
  556. dict?.Add("installpath", newPath);
  557. }
  558. if (dict == null || !dict.ContainsKey("download"))
  559. {
  560. dict?.Add("download", "true");
  561. }
  562. else
  563. {
  564. dict["download"] = "true";
  565. }
  566. }
  567. using FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
  568. using StreamWriter sw = new StreamWriter(fs2);
  569. fs2.SetLength(0);
  570. sw.Write(JsonConvert.SerializeObject(dict));
  571. sw.Flush();
  572. }
  573. }
  574. public class Tencent_cos_download
  575. {
  576. public void download(string download_dir, string key)
  577. {
  578. // download_dir标记根文件夹路径,key为相对根文件夹的路径(不带./)
  579. // 初始化CosXmlConfig(提供配置SDK接口)
  580. string appid = "1314234950"; // 设置腾讯云账户的账户标识(APPID)
  581. string region = "ap-beijing"; // 设置一个默认的存储桶地域
  582. CosXmlConfig config = new CosXmlConfig.Builder()
  583. .IsHttps(true) // 设置默认 HTTPS 请求
  584. .SetAppid(appid) // 设置腾讯云账户的账户标识 APPID
  585. .SetRegion(region) // 设置一个默认的存储桶地域
  586. .SetDebugLog(true) // 显示日志
  587. .Build(); // 创建 CosXmlConfig 对象
  588. // 永久密钥访问凭证
  589. string secretId = "***"; //"云 API 密钥 SecretId";
  590. string secretKey = "***"; //"云 API 密钥 SecretKey";
  591. long durationSecond = 1000; // 每次请求签名有效时长,单位为秒
  592. QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(
  593. secretId, secretKey, durationSecond
  594. );
  595. // 初始化 CosXmlServer
  596. CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);
  597. // 创建存储桶
  598. try
  599. {
  600. string bucket = "thuai6-1314234950"; // 格式:BucketName-APPID
  601. string localDir = System.IO.Path.GetDirectoryName(download_dir) // 本地文件夹
  602. ?? throw new Exception("本地文件夹路径获取失败");
  603. string localFileName = System.IO.Path.GetFileName(download_dir); // 指定本地保存的文件名
  604. GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName);
  605. Dictionary<string, string> test = request.GetRequestHeaders();
  606. request.SetCosProgressCallback(delegate (long completed, long total)
  607. {
  608. //Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
  609. });
  610. // 执行请求
  611. GetObjectResult result = cosXml.GetObject(request);
  612. // 请求成功
  613. }
  614. catch (CosClientException clientEx)
  615. {
  616. throw clientEx;
  617. }
  618. catch (CosServerException serverEx)
  619. {
  620. throw serverEx;
  621. }
  622. catch
  623. {
  624. MessageBox.Show($"下载{download_dir}时出现未知问题,请反馈");
  625. }
  626. }
  627. public static void GetNewHash()
  628. {
  629. Tencent_cos_download Downloader = new Tencent_cos_download();
  630. Downloader.download(System.IO.Path.Combine(Data.FilePath, "hash.json"), "hash.json");
  631. }
  632. public static string GetFileMd5Hash(string strFileFullPath)
  633. {
  634. FileStream? fst = null;
  635. try
  636. {
  637. fst = new FileStream(strFileFullPath, FileMode.Open, FileAccess.Read);
  638. byte[] data = MD5.Create().ComputeHash(fst);
  639. StringBuilder sBuilder = new StringBuilder();
  640. for (int i = 0; i < data.Length; i++)
  641. {
  642. sBuilder.Append(data[i].ToString("x2"));
  643. }
  644. fst.Close();
  645. return sBuilder.ToString().ToLower();
  646. }
  647. catch (Exception)
  648. {
  649. if (fst != null)
  650. fst.Close();
  651. if (File.Exists(strFileFullPath))
  652. return "conflict";
  653. return "";
  654. }
  655. finally
  656. {
  657. }
  658. }
  659. public static bool IsUserFile(string filename)
  660. {
  661. if (filename.Substring(filename.Length - 3, 3).Equals(".sh") || filename.Substring(filename.Length - 4, 4).Equals(".cmd"))
  662. return true;
  663. if (filename.Equals("AI.cpp") || filename.Equals("AI.py"))
  664. return true;
  665. return false;
  666. }
  667. public static UpdateInfo Check(SettingsModel.UsingOS OS)
  668. {
  669. string json, MD5, jsonName;
  670. int newFile = 0, updateFile = 0;
  671. newFileName.Clear();
  672. updateFileName.Clear();
  673. jsonName = "hash.json";
  674. UpdateInfo updateInfo;
  675. Tencent_cos_download Downloader = new Tencent_cos_download();
  676. try
  677. {
  678. // 如果json存在就删了重新下
  679. if (File.Exists(System.IO.Path.Combine(Data.FilePath, jsonName)))
  680. {
  681. File.Delete(System.IO.Path.Combine(Data.FilePath, jsonName));
  682. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  683. }
  684. else
  685. {
  686. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  687. }
  688. }
  689. catch (CosClientException clientEx)
  690. {
  691. // 请求失败
  692. updateInfo.status = "ClientEx: " + clientEx.ToString();
  693. updateInfo.newFileCount = -1;
  694. updateInfo.changedFileCount = 0;
  695. return updateInfo;
  696. }
  697. catch (CosServerException serverEx)
  698. {
  699. // 请求失败
  700. updateInfo.status = "ServerEx: " + serverEx.ToString();
  701. updateInfo.newFileCount = -1;
  702. updateInfo.changedFileCount = 0;
  703. return updateInfo;
  704. }
  705. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, jsonName)))
  706. json = r.ReadToEnd();
  707. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  708. var jsonDict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  709. string updatingFolder = "";
  710. switch (OS)
  711. {
  712. case SettingsModel.UsingOS.Win:
  713. updatingFolder = "THUAI6/win";
  714. break;
  715. case SettingsModel.UsingOS.Linux:
  716. updatingFolder = "THUAI6/lin";
  717. break;
  718. case SettingsModel.UsingOS.OSX:
  719. updatingFolder = "THUAI6/osx";
  720. break;
  721. }
  722. foreach (KeyValuePair<string, string> pair in jsonDict)
  723. {
  724. if (pair.Key.Length > 10 && (pair.Key.Substring(0, 10).Equals(updatingFolder)) || pair.Key.Substring(pair.Key.Length - 4, 4).Equals(".pdf"))
  725. {
  726. MD5 = GetFileMd5Hash(System.IO.Path.Combine(Data.FilePath, pair.Key.TrimStart(new char[] { '.', '/' })));
  727. if (MD5.Length == 0) // 文档不存在
  728. newFileName.Enqueue(pair.Key);
  729. else if (MD5.Equals("conflict"))
  730. {
  731. if (pair.Key.Equals("THUAI6/win/CAPI/cpp/.vs/CAPI/v17/Browse.VC.db"))
  732. {
  733. MessageBox.Show($"visual studio未关闭:\n" +
  734. $"对于visual studio 2022,可以更新,更新会覆盖visual studio中已经打开的选手包;\n" +
  735. $"若使用其他版本的visual studio是继续更新出现问题,请汇报;\n" +
  736. $"若您自行修改了选手包,请注意备份;\n" +
  737. $"若关闭visual studio后仍弹出,请汇报。\n\n",
  738. "visual studio未关闭", MessageBoxButton.OK, MessageBoxImage.Information);
  739. }
  740. else
  741. MessageBox.Show($"检查{pair.Key}更新时遇到问题,请反馈", "读取出错", MessageBoxButton.OK, MessageBoxImage.Error);
  742. }
  743. else if (!MD5.Equals(pair.Value) && !IsUserFile(System.IO.Path.GetFileName(pair.Key))) // MD5不匹配
  744. updateFileName.Enqueue(pair.Key);
  745. }
  746. }
  747. newFile = newFileName.Count;
  748. updateFile = updateFileName.Count;
  749. filenum = newFile + updateFile;
  750. //Console.WriteLine("----------------------" + Environment.NewLine);
  751. if (newFile + updateFile == 0)
  752. {
  753. updateInfo.status = "latest";
  754. updateInfo.newFileCount = 0;
  755. updateInfo.changedFileCount = 0;
  756. newFileName.Clear();
  757. updateFileName.Clear();
  758. }
  759. else
  760. {
  761. updateInfo.status = "old";
  762. //TODO:获取版本号
  763. updateInfo.newFileCount = newFile;
  764. /*
  765. foreach (string filename in newFileName)
  766. {
  767. Console.WriteLine(filename);
  768. }
  769. */
  770. updateInfo.changedFileCount = updateFile;
  771. /*
  772. foreach (string filename in updateFileName)
  773. {
  774. Console.WriteLine(filename);
  775. }
  776. Console.Write(Environment.NewLine + "是否下载新文件? y/n:");
  777. if (Console.Read() != 'y')
  778. Console.WriteLine("下载取消!");
  779. else
  780. Download();
  781. */
  782. UpdatePlanned = true;
  783. }
  784. return updateInfo;
  785. }
  786. public static bool Update()
  787. {
  788. if (UpdatePlanned)
  789. {
  790. Download();
  791. if (updateFailed.Count == 0)
  792. return true;
  793. }
  794. return false;
  795. }
  796. private static void Download()
  797. {
  798. Tencent_cos_download Downloader = new Tencent_cos_download();
  799. int newFile = 0;
  800. int totalnew = newFileName.Count, totalupdate = updateFileName.Count;
  801. filenum = totalnew + totalupdate;
  802. updateFailed.Clear();
  803. if (newFileName.Count > 0 || updateFileName.Count > 0)
  804. {
  805. try
  806. {
  807. int cnt = newFileName.Count;
  808. if (cnt <= 20)
  809. {
  810. while (newFileName.TryDequeue(out var filename))
  811. {
  812. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename.TrimStart(new char[] { '.', '/' }));
  813. //Console.WriteLine(filename + "下载完毕!" + Environment.NewLine);
  814. Interlocked.Increment(ref newFile);
  815. }
  816. }
  817. else
  818. {
  819. const int nthread = 8;
  820. var thrds = new List<Thread>();
  821. for (int i = 0; i < nthread; i++)
  822. {
  823. var thrd = new Thread(() =>
  824. {
  825. while (newFileName.TryDequeue(out var filename))
  826. {
  827. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename.TrimStart(new char[] { '.', '/' }));
  828. //Console.WriteLine(filename + "下载完毕!" + Environment.NewLine);
  829. Interlocked.Increment(ref newFile);
  830. }
  831. });
  832. thrd.Start();
  833. thrds.Add(thrd);
  834. }
  835. foreach (var thrd in thrds)
  836. {
  837. thrd.Join();
  838. }
  839. }
  840. // 读取 Interlocked.CompareExchange(ref newFile, 0, 0);
  841. int upcnt = updateFileName.Count;
  842. if (upcnt <= 20)
  843. {
  844. while (updateFileName.TryDequeue(out var filename))
  845. {
  846. try
  847. {
  848. File.Delete(System.IO.Path.Combine(@Data.FilePath, filename));
  849. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename.TrimStart(new char[] { '.', '/' }));
  850. }
  851. catch (System.IO.IOException)
  852. {
  853. updateFailed = updateFailed.Append(filename).ToList();
  854. }
  855. catch
  856. {
  857. if (filename.Substring(filename.Length - 4, 4).Equals(".pdf"))
  858. {
  859. MessageBox.Show($"由于曾经发生过的访问冲突,下载器无法更新{filename}\n"
  860. + $"请手动删除{filename},然后再试一次。");
  861. }
  862. else
  863. MessageBox.Show($"更新{filename}时遇到未知问题,请反馈");
  864. updateFailed = updateFailed.Append(filename).ToList();
  865. }
  866. Interlocked.Increment(ref newFile);
  867. }
  868. }
  869. else
  870. {
  871. const int nthread = 8;
  872. var thrds = new List<Thread>();
  873. for (int i = 0; i < nthread; i++)
  874. {
  875. var thrd = new Thread(() =>
  876. {
  877. while (updateFileName.TryDequeue(out var filename))
  878. {
  879. try
  880. {
  881. File.Delete(System.IO.Path.Combine(@Data.FilePath, filename));
  882. Downloader.download(System.IO.Path.Combine(@Data.FilePath, filename), filename.TrimStart(new char[] { '.', '/' }));
  883. }
  884. catch (System.IO.IOException)
  885. {
  886. updateFailed = updateFailed.Append(filename).ToList();
  887. }
  888. catch
  889. {
  890. if (filename.Substring(filename.Length - 4, 4).Equals(".pdf"))
  891. {
  892. MessageBox.Show($"由于曾经发生过的访问冲突,下载器无法更新{filename}\n"
  893. + $"请手动删除{filename},然后再试一次。");
  894. }
  895. else
  896. MessageBox.Show($"更新{filename}时遇到未知问题,请反馈");
  897. updateFailed = updateFailed.Append(filename).ToList();
  898. }
  899. Interlocked.Increment(ref newFile);
  900. }
  901. });
  902. thrd.Start();
  903. thrds.Add(thrd);
  904. }
  905. foreach (var thrd in thrds)
  906. {
  907. thrd.Join();
  908. }
  909. }
  910. if (updateFailed.Count == 0)
  911. UpdatePlanned = false;
  912. }
  913. catch (CosClientException clientEx)
  914. {
  915. // 请求失败
  916. MessageBox.Show("连接错误:" + clientEx.ToString());
  917. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  918. return;
  919. }
  920. catch (CosServerException serverEx)
  921. {
  922. // 请求失败
  923. MessageBox.Show("连接错误:" + serverEx.ToString());
  924. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  925. return;
  926. }
  927. catch (Exception)
  928. {
  929. MessageBox.Show("未知错误且无法定位到出错文件,请反馈");
  930. throw;
  931. }
  932. }
  933. else
  934. Console.WriteLine("当前平台已是最新版本!" + Environment.NewLine);
  935. newFileName.Clear();
  936. updateFileName.Clear();
  937. }
  938. public static bool CheckAlreadyDownload() // 检查是否已经下载
  939. {
  940. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  941. if (!File.Exists(existpath)) // 文件不存在
  942. {
  943. using FileStream fs = new FileStream(existpath, FileMode.Create, FileAccess.ReadWrite);
  944. return false;
  945. }
  946. else // 文件存在
  947. {
  948. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.Read);
  949. using StreamReader sr = new StreamReader(fs);
  950. string json = sr.ReadToEnd();
  951. if (json == null || json == "")
  952. {
  953. json += @"{""THUAI6""" + ":" + @"""2023""}";
  954. }
  955. var dict = Utils.TryDeserializeJson<Dictionary<string, string>>(json);
  956. if (dict == null || !dict.ContainsKey("download") || "false" == dict["download"])
  957. {
  958. return false;
  959. }
  960. else if (dict["download"] == "true")
  961. {
  962. return true;
  963. }
  964. else
  965. {
  966. return false;
  967. }
  968. }
  969. }
  970. public static void DownloadAll() // 下载全部文件
  971. {
  972. string jsonName = "hash.json";
  973. string json;
  974. Tencent_cos_download Downloader = new Tencent_cos_download();
  975. try
  976. {
  977. // 如果json存在就删了重新下
  978. if (File.Exists(System.IO.Path.Combine(Data.FilePath, jsonName)))
  979. {
  980. File.Delete(System.IO.Path.Combine(Data.FilePath, jsonName));
  981. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  982. }
  983. else
  984. {
  985. Downloader.download(System.IO.Path.Combine(Data.FilePath, jsonName), jsonName);
  986. }
  987. }
  988. catch (CosClientException clientEx)
  989. {
  990. // 请求失败
  991. Console.WriteLine("CosClientException: " + clientEx.ToString() + Environment.NewLine);
  992. return;
  993. }
  994. catch (CosServerException serverEx)
  995. {
  996. // 请求失败
  997. Console.WriteLine("CosClientException: " + serverEx.ToString() + Environment.NewLine);
  998. return;
  999. }
  1000. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, jsonName)))
  1001. json = r.ReadToEnd();
  1002. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  1003. // var jsonDict = Utils.DeserializeJson<Dictionary1<string, string>>(json);
  1004. newFileName.Clear();
  1005. updateFileName.Clear();
  1006. newFileName.Enqueue("THUAI6.tar.gz");
  1007. Download();
  1008. Stream? inStream = null;
  1009. Stream? gzipStream = null;
  1010. TarArchive? tarArchive = null;
  1011. try
  1012. {
  1013. using (inStream = File.OpenRead(System.IO.Path.Combine(Data.FilePath, "THUAI6.tar.gz")))
  1014. {
  1015. using (gzipStream = new GZipInputStream(inStream))
  1016. {
  1017. tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
  1018. tarArchive.ExtractContents(Data.FilePath);
  1019. tarArchive.Close();
  1020. }
  1021. }
  1022. }
  1023. catch
  1024. {
  1025. //出错
  1026. }
  1027. finally
  1028. {
  1029. if (null != tarArchive) tarArchive.Close();
  1030. if (null != gzipStream) gzipStream.Close();
  1031. if (null != inStream) inStream.Close();
  1032. }
  1033. FileInfo fileInfo = new FileInfo(System.IO.Path.Combine(Data.FilePath, "THUAI6.tar.gz"));
  1034. fileInfo.Delete();
  1035. string json2;
  1036. Dictionary<string, string>? dict;
  1037. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1038. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  1039. using (StreamReader r = new StreamReader(fs))
  1040. {
  1041. json2 = r.ReadToEnd();
  1042. if (json2 == null || json2 == "")
  1043. {
  1044. json2 += @"{""THUAI6""" + ":" + @"""2023""}";
  1045. }
  1046. dict = Utils.TryDeserializeJson<Dictionary<string, string>>(json2);
  1047. if (dict == null || !dict.ContainsKey("download"))
  1048. {
  1049. dict?.Add("download", "true");
  1050. }
  1051. else
  1052. {
  1053. dict["download"] = "true";
  1054. }
  1055. }
  1056. using FileStream fs2 = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  1057. using StreamWriter sw = new StreamWriter(fs2);
  1058. fs2.SetLength(0);
  1059. sw.Write(JsonConvert.SerializeObject(dict));
  1060. Check(SettingsModel.UsingOS.Win);
  1061. Download();
  1062. if (File.Exists(Data.FilePath + "/THUAI6/AI.cpp"))
  1063. {
  1064. FileInfo userCpp = new FileInfo((Data.FilePath + "/THUAI6/AI.cpp").Replace("/", "\\"));
  1065. userCpp.MoveTo(Data.FilePath + "/THUAI6/win/CAPI/cpp/API/src/AI.cpp", true);
  1066. }
  1067. if (File.Exists(Data.FilePath + "/THUAI6/AI.py"))
  1068. {
  1069. FileInfo userCpp = new FileInfo((Data.FilePath + "/THUAI6/AI.py").Replace("/", "\\"));
  1070. userCpp.MoveTo(Data.FilePath + "/THUAI6/win/CAPI/python/PyAPI/AI.cpp", true);
  1071. }
  1072. }
  1073. public static void Change_all_hash(string topDir, Dictionary<string, string> jsonDict) // 更改HASH
  1074. {
  1075. DirectoryInfo theFolder = new DirectoryInfo(@topDir);
  1076. bool ifexist = false;
  1077. // 遍历文件
  1078. foreach (FileInfo NextFile in theFolder.GetFiles())
  1079. {
  1080. string filepath = topDir + @"/" + NextFile.Name; // 文件路径
  1081. //Console.WriteLine(filepath);
  1082. foreach (KeyValuePair<string, string> pair in jsonDict)
  1083. {
  1084. if (System.IO.Path.Equals(filepath, System.IO.Path.Combine(Data.FilePath, pair.Key).Replace('\\', '/')))
  1085. {
  1086. ifexist = true;
  1087. string MD5 = GetFileMd5Hash(filepath);
  1088. jsonDict[pair.Key] = MD5;
  1089. }
  1090. }
  1091. if (!ifexist && NextFile.Name != "hash.json")
  1092. {
  1093. string MD5 = GetFileMd5Hash(filepath);
  1094. string relapath = filepath.Replace(Data.FilePath + '/', string.Empty);
  1095. jsonDict.Add(relapath, MD5);
  1096. }
  1097. ifexist = false;
  1098. }
  1099. // 遍历文件夹
  1100. foreach (DirectoryInfo NextFolder in theFolder.GetDirectories())
  1101. {
  1102. if (System.IO.Path.Equals(NextFolder.FullName, System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder))))
  1103. {
  1104. foreach (FileInfo NextFile in NextFolder.GetFiles())
  1105. {
  1106. if (NextFile.Name == "AI.cpp" || NextFile.Name == "AI.py")
  1107. {
  1108. string MD5 = GetFileMd5Hash(NextFile.FullName);
  1109. string relapath = NextFile.FullName.Replace('\\', '/').Replace(Data.FilePath + '/', string.Empty);
  1110. jsonDict.Add(relapath, MD5);
  1111. }
  1112. }
  1113. continue; // 如果是选手文件夹就忽略
  1114. }
  1115. Change_all_hash(NextFolder.FullName.Replace('\\', '/'), jsonDict);
  1116. }
  1117. }
  1118. public static void UpdateHash()
  1119. {
  1120. while (true)
  1121. {
  1122. if (Directory.Exists(Data.FilePath))
  1123. {
  1124. string json;
  1125. if (!File.Exists(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  1126. {
  1127. Console.WriteLine("hash.json文件丢失!即将重新下载该文件!");
  1128. GetNewHash();
  1129. }
  1130. using (StreamReader r = new StreamReader(System.IO.Path.Combine(Data.FilePath, "hash.json")))
  1131. json = r.ReadToEnd();
  1132. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("/", @"\\");
  1133. Dictionary<string, string> jsonDict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  1134. Change_all_hash(Data.FilePath, jsonDict);
  1135. OverwriteHash(jsonDict);
  1136. break;
  1137. }
  1138. else
  1139. {
  1140. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  1141. Data.ResetFilepath(Console.ReadLine() ?? "");
  1142. }
  1143. }
  1144. }
  1145. public static int DeleteAll()
  1146. {
  1147. DirectoryInfo di = new DirectoryInfo(Data.FilePath + "/THUAI6");
  1148. //DirectoryInfo player = new DirectoryInfo(System.IO.Path.GetFullPath(System.IO.Path.Combine(Data.FilePath, playerFolder)));
  1149. FileInfo[] allfile = di.GetFiles();
  1150. try
  1151. {
  1152. foreach (FileInfo file in allfile)
  1153. {
  1154. //if(file.Name == "AI.cpp" || file.Name == "AI.py")
  1155. //{
  1156. // string filename = System.IO.Path.GetFileName(file.FullName);
  1157. // file.MoveTo(System.IO.Path.Combine(Data.FilePath, filename));
  1158. // continue;
  1159. //}
  1160. file.Delete();
  1161. }
  1162. FileInfo userFileCpp = new FileInfo(Data.FilePath + "/THUAI6/win/CAPI/cpp/API/src/AI.cpp");
  1163. FileInfo userFilePy = new FileInfo(Data.FilePath + "/THUAI6/win/CAPI/python/PyAPI/AI.py");
  1164. userFileCpp.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", System.IO.Path.GetFileName(userFileCpp.FullName)));
  1165. userFilePy.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", System.IO.Path.GetFileName(userFilePy.FullName)));
  1166. foreach (DirectoryInfo subdi in di.GetDirectories())
  1167. {
  1168. subdi.Delete(true);
  1169. }
  1170. FileInfo hashFile = new FileInfo(Data.FilePath + "/hash.json");
  1171. hashFile.Delete();
  1172. }
  1173. catch (UnauthorizedAccessException)
  1174. {
  1175. Console.WriteLine("权限不足,无法删除!");
  1176. return -2;
  1177. }
  1178. catch (DirectoryNotFoundException)
  1179. {
  1180. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  1181. return -3;
  1182. }
  1183. catch (IOException)
  1184. {
  1185. Console.WriteLine("文件已经打开,请关闭后再删除");
  1186. return -1;
  1187. }
  1188. string json2;
  1189. Dictionary<string, string>? dict;
  1190. string existpath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1191. using FileStream fs = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  1192. using (StreamReader r = new StreamReader(fs))
  1193. {
  1194. json2 = r.ReadToEnd();
  1195. if (json2 == null || json2 == "")
  1196. {
  1197. json2 += @"{""THUAI6""" + ":" + @"""2023""}";
  1198. }
  1199. dict = Utils.TryDeserializeJson<Dictionary<string, string>>(json2);
  1200. if (dict == null || !dict.ContainsKey("download"))
  1201. {
  1202. dict?.Add("download", "false");
  1203. }
  1204. else
  1205. {
  1206. dict["download"] = "false";
  1207. }
  1208. }
  1209. using FileStream fs2 = new FileStream(existpath, FileMode.Open, FileAccess.ReadWrite);
  1210. using StreamWriter sw = new StreamWriter(fs2);
  1211. fs2.SetLength(0);
  1212. sw.Write(JsonConvert.SerializeObject(dict));
  1213. sw.Close();
  1214. fs2.Close();
  1215. try
  1216. {
  1217. File.Delete(Data.path);
  1218. }
  1219. catch (UnauthorizedAccessException)
  1220. {
  1221. Console.WriteLine("权限不足,无法删除!");
  1222. return -2;
  1223. }
  1224. catch (DirectoryNotFoundException)
  1225. {
  1226. Console.WriteLine("文件夹没有找到,请检查是否已经手动更改路径");
  1227. return -3;
  1228. }
  1229. catch (IOException)
  1230. {
  1231. Console.WriteLine("文件已经打开,请关闭后再删除");
  1232. return -1;
  1233. }
  1234. return 0;
  1235. }
  1236. public static void OverwriteHash(Dictionary<string, string> jsonDict)
  1237. {
  1238. string Contentjson = JsonConvert.SerializeObject(jsonDict);
  1239. Contentjson = Contentjson.Replace("\r", String.Empty).Replace("\n", String.Empty).Replace(@"\\", "/");
  1240. File.WriteAllText(@System.IO.Path.Combine(Data.FilePath, "hash.json"), Contentjson);
  1241. }
  1242. public static int MoveProgram(string newPath)
  1243. {
  1244. DirectoryInfo newdi = new DirectoryInfo(newPath + "/THUAI6");
  1245. DirectoryInfo olddi = new DirectoryInfo(Data.FilePath + "/THUAI6");
  1246. try
  1247. {
  1248. if (!Directory.Exists(newPath + "/THUAI6"))
  1249. Directory.CreateDirectory(newPath + "/THUAI6");
  1250. foreach (DirectoryInfo direct in olddi.GetDirectories())
  1251. {
  1252. direct.MoveTo(System.IO.Path.Combine(newPath + "/THUAI6", direct.Name));
  1253. }
  1254. foreach (FileInfo file in olddi.GetFiles())
  1255. {
  1256. file.MoveTo(System.IO.Path.Combine(newPath + "/THUAI6", file.Name));
  1257. }
  1258. olddi.Delete();
  1259. }
  1260. catch (DirectoryNotFoundException)
  1261. {
  1262. Console.WriteLine("原路径未找到!请检查文件是否损坏");
  1263. if (newdi.GetDirectories().Length != 0)
  1264. {
  1265. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  1266. {
  1267. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", newdirect.Name));
  1268. }
  1269. }
  1270. if (newdi.GetFiles().Length != 0)
  1271. {
  1272. foreach (FileInfo file in newdi.GetFiles())
  1273. {
  1274. file.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", file.Name));
  1275. }
  1276. }
  1277. Console.WriteLine("移动失败!");
  1278. if (newdi.Exists)
  1279. newdi.Delete();
  1280. return -2;
  1281. }
  1282. catch (IOException)
  1283. {
  1284. Console.WriteLine("文件已打开或者目标路径下有同名文件!");
  1285. if (newdi.GetDirectories().Length != 0)
  1286. {
  1287. foreach (DirectoryInfo newdirect in newdi.GetDirectories())
  1288. {
  1289. newdirect.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", newdirect.Name));
  1290. }
  1291. }
  1292. if (newdi.GetFiles().Length != 0)
  1293. {
  1294. foreach (FileInfo file in newdi.GetFiles())
  1295. {
  1296. file.MoveTo(System.IO.Path.Combine(Data.FilePath + "/THUAI6", file.Name));
  1297. }
  1298. }
  1299. if (newdi.Exists)
  1300. newdi.Delete();
  1301. Console.WriteLine("移动失败!");
  1302. return -1;
  1303. }
  1304. FileInfo hashFile = new FileInfo(Data.FilePath + "/hash.json");
  1305. hashFile.MoveTo(newPath + "/hash.json");
  1306. Data.ResetFilepath(newPath);
  1307. Console.WriteLine("更改路径成功!");
  1308. return 0;
  1309. }
  1310. public static async Task main(string[] args)
  1311. {
  1312. var client = new HttpClient();
  1313. var web = new WebConnect.Web();
  1314. Data date = new Data("");
  1315. while (true)
  1316. {
  1317. Console.WriteLine($"1. 更新hash.json 2. 检查更新 3.下载{ProgramName} 4.删除{ProgramName} 5.启动进程 6.移动{ProgramName}到其它路径");
  1318. string choose = Console.ReadLine() ?? "";
  1319. if (choose == "1")
  1320. {
  1321. if (!CheckAlreadyDownload())
  1322. {
  1323. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  1324. continue;
  1325. }
  1326. UpdateHash();
  1327. }
  1328. else if (choose == "2")
  1329. {
  1330. if (!CheckAlreadyDownload())
  1331. {
  1332. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  1333. continue;
  1334. }
  1335. while (true)
  1336. {
  1337. if (Data.FilePath != null && Directory.Exists(Data.FilePath))
  1338. {
  1339. Check(SettingsModel.UsingOS.Win);
  1340. break;
  1341. }
  1342. else
  1343. {
  1344. Console.WriteLine("读取路径失败!请重新输入文件路径:");
  1345. Data.ResetFilepath(Console.ReadLine() ?? "");
  1346. }
  1347. }
  1348. }
  1349. else if (choose == "3")
  1350. {
  1351. if (CheckAlreadyDownload())
  1352. {
  1353. Console.WriteLine($"已经将{ProgramName}下载到{Data.FilePath}!若要重新下载请先完成删除操作!");
  1354. }
  1355. else
  1356. {
  1357. string newpath;
  1358. Console.WriteLine("请输入下载路径:");
  1359. newpath = Console.ReadLine() ?? "";
  1360. Data.ResetFilepath(newpath);
  1361. DownloadAll();
  1362. }
  1363. }
  1364. else if (choose == "4")
  1365. {
  1366. DeleteAll();
  1367. }
  1368. else if (choose == "5")
  1369. {
  1370. if (CheckAlreadyDownload())
  1371. {
  1372. Process.Start(System.IO.Path.Combine(Data.FilePath, startName));
  1373. }
  1374. else
  1375. {
  1376. Console.WriteLine($"未下载{ProgramName},请先执行下载操作!");
  1377. }
  1378. }
  1379. else if (choose == "6")
  1380. {
  1381. string newPath;
  1382. newPath = Console.ReadLine() ?? "";
  1383. MoveProgram(newPath);
  1384. }
  1385. else if (choose == "7")
  1386. {
  1387. Console.WriteLine("请输入email:");
  1388. string username = Console.ReadLine() ?? "";
  1389. Console.WriteLine("请输入密码:");
  1390. string password = Console.ReadLine() ?? "";
  1391. await web.LoginToEEsast(client, username, password);
  1392. }
  1393. else if (choose == "8")
  1394. {
  1395. await web.UserDetails(client);
  1396. }
  1397. else if (choose == "9")
  1398. {
  1399. await web.UploadFiles(client, "", "", "");
  1400. }
  1401. else if (choose == "exit")
  1402. {
  1403. return;
  1404. }
  1405. }
  1406. }
  1407. public static int CheckSelfVersion()
  1408. {
  1409. string keyHead = "Installer/";
  1410. Tencent_cos_download downloader = new Tencent_cos_download();
  1411. string hashName = "installerHash.json";
  1412. string dir = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName)
  1413. ?? throw new Exception("Failed to get current directory");
  1414. int result = 0;
  1415. try
  1416. {
  1417. if (File.Exists(System.IO.Path.Combine(dir, hashName)))
  1418. File.Delete(System.IO.Path.Combine(dir, hashName));
  1419. downloader.download(System.IO.Path.Combine(dir, hashName), hashName);
  1420. }
  1421. catch
  1422. {
  1423. return -1;
  1424. }
  1425. string json;
  1426. using (StreamReader r = new StreamReader(System.IO.Path.Combine(dir, hashName)))
  1427. json = r.ReadToEnd();
  1428. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  1429. var jsonDict = Utils.TryDeserializeJson<Dictionary<string, string>>(json);
  1430. string md5 = "";
  1431. List<string> awaitUpdate = new List<string>();
  1432. if (jsonDict != null)
  1433. {
  1434. foreach (KeyValuePair<string, string> pair in jsonDict)
  1435. {
  1436. md5 = GetFileMd5Hash(System.IO.Path.Combine(dir, pair.Key));
  1437. if (md5.Length == 0) // 文档不存在
  1438. {
  1439. downloader.download(System.IO.Path.Combine(dir, pair.Key), keyHead + pair.Key);
  1440. }
  1441. else if (md5.Equals("conflict"))
  1442. {
  1443. MessageBox.Show($"检查{pair.Key}更新时遇到问题,请反馈", "读取出错", MessageBoxButton.OK, MessageBoxImage.Error);
  1444. }
  1445. else if (md5 != pair.Value) // MD5不匹配
  1446. {
  1447. if (pair.Key.Substring(0, 12).Equals("InstallerUpd"))
  1448. {
  1449. File.Delete(System.IO.Path.Combine(dir, pair.Key));
  1450. downloader.download(System.IO.Path.Combine(dir, pair.Key), keyHead + pair.Key);
  1451. }
  1452. else
  1453. {
  1454. result = 1;
  1455. awaitUpdate = awaitUpdate.Append(pair.Key).ToList();
  1456. }
  1457. }
  1458. }
  1459. }
  1460. else
  1461. return -1;
  1462. string Contentjson = JsonConvert.SerializeObject(awaitUpdate);
  1463. Contentjson = Contentjson.Replace("\r", String.Empty).Replace("\n", String.Empty).Replace(@"\\", "/");
  1464. File.WriteAllText(@System.IO.Path.Combine(dir, "updateList.json"), Contentjson);
  1465. return result;
  1466. }
  1467. static public bool SelfUpdateDismissed()
  1468. {
  1469. string json;
  1470. string dir = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName)
  1471. ?? throw new Exception("Failed to get directory!");
  1472. if (!File.Exists(System.IO.Path.Combine(dir, "updateList.json")))
  1473. return false;
  1474. using (StreamReader r = new StreamReader(System.IO.Path.Combine(dir, "updateList.json")))
  1475. json = r.ReadToEnd();
  1476. json = json.Replace("\r", string.Empty).Replace("\n", string.Empty);
  1477. List<string>? jsonList;
  1478. if (json != null)
  1479. jsonList = Utils.TryDeserializeJson<List<string>>(json);
  1480. else
  1481. return false;
  1482. if (jsonList != null && jsonList.Contains("Dismiss"))
  1483. {
  1484. listJsonClear(System.IO.Path.Combine(dir, "updateList.json"));
  1485. return true;
  1486. }
  1487. return false;
  1488. }
  1489. static private void listJsonClear(string directory)
  1490. {
  1491. List<string> list = new List<string>();
  1492. list.Add("None");
  1493. StreamWriter sw = new StreamWriter(directory, false);
  1494. sw.WriteLine(JsonConvert.SerializeObject(list));
  1495. sw.Close();
  1496. }
  1497. }
  1498. public class RunProgram
  1499. {
  1500. public enum RunMode
  1501. {
  1502. ServerOnly, //只启动Server
  1503. ServerForDebugOnly, //只启动ServerForDebug
  1504. GUIAttendGameOnly, //只用GUIClient参与游戏
  1505. GUIVisit, //只用GUIClient观战
  1506. GUIAndAICpp, //用GUI参与游戏并且让cpp的AI同时参与
  1507. GUIAndAIPython, //用GUI参与游戏并且让python的AI同时参与
  1508. ServerAndCpp, //只运行Server和cpp,
  1509. ServerAndPython, //只运行Server和python
  1510. ServerAndCppVisit, //运行Server和Cpp并用GUI观战
  1511. ServerAndPythonVisit, //运行Server和python并用GUI观战
  1512. ServerDebugAndCpp, //运行ServerForDebug...
  1513. ServerDebugAndPython,
  1514. ServerDebugAndCppVisit,
  1515. ServerDebugAndPythonVisit,
  1516. }
  1517. // !!! 目前此类的各个静态成员从未被赋值过
  1518. public class RunInfo //UI需要在调用Launch函数前保证其中数据已经更新并有效
  1519. {
  1520. public static RunMode mode = default;
  1521. public static string? IP = null;
  1522. public static int port = 0;
  1523. public static int studentCount = 0;
  1524. public static int trickerCount = 0;
  1525. public static int gameTimeSec = 0;
  1526. public static string? playbackFileName = null;
  1527. public static int characterID = 0;
  1528. public static int type = 0;
  1529. public static bool saveDebugLog = false;
  1530. public static bool showDebugLog = false;
  1531. public static bool warningOnly = false;
  1532. public static bool visiting = false;
  1533. public static int occupation = 0;
  1534. public static List<int>? playerId = new List<int>(); //两者长度必须与studentCount + trickerCount一致
  1535. public static List<string>? filePath = new List<string>();
  1536. }
  1537. /// <summary>
  1538. /// 运行cmd命令
  1539. /// 会显示命令窗口
  1540. /// </summary>
  1541. /// <param name="cmdExe">指定应用程序的完整路径</param>
  1542. /// <param name="cmdStr">执行命令行参数</param>
  1543. static bool RunCmd(string cmdExe, string cmdStr)
  1544. {
  1545. bool result = false;
  1546. try
  1547. {
  1548. using (Process myPro = new Process())
  1549. {
  1550. //指定启动进程是调用的应用程序和命令行参数
  1551. ProcessStartInfo psi = new ProcessStartInfo(cmdExe, cmdStr);
  1552. myPro.StartInfo = psi;
  1553. myPro.Start();
  1554. //myPro.WaitForExitAsync();
  1555. result = true;
  1556. }
  1557. }
  1558. catch
  1559. {
  1560. }
  1561. return result;
  1562. }
  1563. /// <summary>
  1564. /// 启动Server
  1565. /// 会显示命令窗口
  1566. /// </summary>
  1567. /// <param name="IP">指定Server运行的IPV4地址</param>
  1568. /// <param name="port">指定Server运行的端口</param>
  1569. /// <param name="studentCount">指定学生人数</param>
  1570. /// <param name="trickerCount">指定捣蛋鬼人数</param>
  1571. /// <param name="gameTimeSec">指定游戏最大时长</param>
  1572. /// <param name="playbackFileName">指定回放文件名称</param>
  1573. public static int StartServer(string? IP, int port, int studentCount, int trickerCount, int gameTimeSec, string? playbackFileName)
  1574. {
  1575. if (System.Diagnostics.Process.GetProcessesByName("Server").ToList().Count > 0)
  1576. {
  1577. System.Diagnostics.Process.GetProcessesByName("Server")[0].Kill();
  1578. }
  1579. string cmdExe = $"{Data.FilePath}\\THUAI6\\win\\win64\\Server.exe";
  1580. string cmdPara = $"--ip {IP} --port {port} --studentCount {studentCount} --trickerCount {trickerCount}" +
  1581. $" --gameTimeInSecond {gameTimeSec} --fileName {playbackFileName}";
  1582. RunCmd(cmdExe, cmdPara);
  1583. return 0;
  1584. }
  1585. /// <summary>
  1586. /// 启动Debug用的Server
  1587. /// 会显示命令窗口
  1588. /// </summary>
  1589. /// <param name="IP">指定Server运行的IPV4地址</param>
  1590. /// <param name="port">指定Server运行的端口</param>
  1591. /// <param name="studentCount">指定学生人数</param>
  1592. /// <param name="trickerCount">指定捣蛋鬼人数</param>
  1593. /// <param name="gameTimeSec">指定游戏最大时长</param>
  1594. /// <param name="playbackFileName">指定回放文件名称</param>
  1595. public static int StartServerForDebug(string? IP, int port, int studentCount, int trickerCount, int gameTimeSec, string? playbackFileName)
  1596. {
  1597. if (System.Diagnostics.Process.GetProcessesByName("Server").ToList().Count > 0)
  1598. {
  1599. System.Diagnostics.Process.GetProcessesByName("Server")[0].Kill();
  1600. }
  1601. string cmdExe = $"{Data.FilePath}\\THUAI6\\win\\win64\\Debug\\Server.exe";
  1602. string cmdPara = $"--ip {IP} --port {port} --studentCount {studentCount} --trickerCount {trickerCount} " +
  1603. $"--gameTimeInSecond {gameTimeSec} --fileName {playbackFileName}";
  1604. RunCmd(cmdExe, cmdPara);
  1605. return 0;
  1606. }
  1607. /// <summary>
  1608. /// 启动cpp,在这之前要先启动Server,可能还需要一些延时
  1609. /// 会显示命令窗口
  1610. /// </summary>
  1611. /// <param name="IP">指定Server运行的IPV4地址</param>
  1612. /// <param name="port">指定Server运行的端口</param>
  1613. /// <param name="studentCount">指定学生人数</param>
  1614. /// <param name="trickerCount">指定捣蛋鬼人数</param>
  1615. /// <param name="saveDebugLog">是否保存Debug日志文件</param>
  1616. /// <param name="showDebugLog">是否将日志输出到屏幕上</param>
  1617. /// <param name="warningOnly">在showDebugLog == true时,是否只输出警告或者报错(不影响日志保存)</param>
  1618. /// <param name="playerIp">默认为空,如果不为空,playerIp将会按照顺序代替默认从0~3的IP</param>
  1619. public static int RunCpp(string? IP, int port, int studentCount, int trickerCount, bool saveDebugLog,
  1620. bool showDebugLog, bool warningOnly, List<int>? playerIp = null, List<string>? filePath = null)
  1621. {
  1622. string cmdExe;
  1623. string cmdBase = $"-I {IP} -P {port} ";
  1624. for (int i = 0; i < studentCount; i++)
  1625. {
  1626. string cmdPara;
  1627. if (playerIp == null)
  1628. {
  1629. cmdPara = cmdBase + $" -p {i}";
  1630. }
  1631. else
  1632. {
  1633. cmdPara = cmdBase + $" -p {playerIp[i]}";
  1634. }
  1635. if (saveDebugLog)
  1636. {
  1637. cmdPara = cmdPara + " -d";
  1638. }
  1639. if (showDebugLog)
  1640. {
  1641. cmdPara = cmdPara + " -o";
  1642. }
  1643. if (warningOnly)
  1644. {
  1645. cmdPara = cmdPara + " -w";
  1646. }
  1647. if (filePath == null)
  1648. {
  1649. cmdExe = $"{Data.FilePath}\\THUAI6\\win\\CAPI\\cpp\\x64\\Debug\\API.exe";
  1650. }
  1651. else
  1652. {
  1653. cmdExe = filePath[i];
  1654. }
  1655. RunCmd(cmdExe, cmdPara);
  1656. }
  1657. if (trickerCount != 0)
  1658. {
  1659. string cmdPara;
  1660. cmdPara = cmdBase + " -p 4";
  1661. if (saveDebugLog)
  1662. {
  1663. cmdPara = cmdPara + " -d";
  1664. }
  1665. if (showDebugLog)
  1666. {
  1667. cmdPara = cmdPara + " -o";
  1668. }
  1669. if (warningOnly)
  1670. {
  1671. cmdPara = cmdPara + " -w";
  1672. }
  1673. if (filePath == null)
  1674. {
  1675. cmdExe = $"{Data.FilePath}\\THUAI6\\win\\CAPI\\cpp\\x64\\Debug\\API.exe";
  1676. }
  1677. else
  1678. {
  1679. cmdExe = filePath[studentCount];
  1680. }
  1681. RunCmd(cmdExe, cmdPara);
  1682. }
  1683. return 0;
  1684. }
  1685. /// <summary>
  1686. /// 启动客户端
  1687. /// 会显示命令窗口
  1688. /// </summary>
  1689. /// <param name="IP">指定Server运行的IPV4地址</param>
  1690. /// <param name="port">指定Server运行的端口</param>
  1691. /// <param name="characterID">进入游戏时的角色ID 0~4,0~3为学生,4为捣蛋鬼</param>
  1692. /// <param name="visiting">是否观战,当值为true时,characterID无效</param>
  1693. /// <param name="occupation">指定参加游戏时的角色职业,详情见说明文档</param>
  1694. /// <param name="type">角色类别,type = 1 表示学生,type = 2 表示捣蛋鬼</param>
  1695. public static int RunGUIClient(string? IP, int port, int characterID, bool visiting, int occupation = 1, int type = 1)
  1696. {
  1697. string cmdExe = $"{Data.FilePath}\\THUAI6\\win\\win64\\Client.exe";
  1698. string cmdBase = $"--port {port} --ip {IP} --type {type} --occupation {occupation}";
  1699. if (visiting)
  1700. {
  1701. cmdBase = cmdBase + " --characterID 200000";
  1702. }
  1703. else
  1704. {
  1705. cmdBase = cmdBase + $" --characterID {characterID}";
  1706. }
  1707. cmdBase = cmdBase + " --cl";
  1708. RunCmd(cmdExe, cmdBase);
  1709. return 0;
  1710. }
  1711. //启动python,参数同RunCpp
  1712. public static int RunPython(string? IP, int port, int studentCount, int trickerCount, bool saveDebugLog,
  1713. bool showDebugLog, bool warningOnly, List<int>? playerIp = null, List<string>? filePath = null)
  1714. {
  1715. string cmdExe = $"python";
  1716. string cmdBase;
  1717. for (int i = 0; i < studentCount; i++)
  1718. {
  1719. string cmdPara;
  1720. if (filePath == null)
  1721. {
  1722. cmdBase = $" {Data.FilePath}\\THUAI6\\win\\CAPI\\python\\PyAPI\\main.py -I {IP} -P {port} ";
  1723. }
  1724. else
  1725. {
  1726. cmdBase = " " + filePath[i] + $" -I {IP} -P {port} ";
  1727. }
  1728. if (playerIp == null)
  1729. {
  1730. cmdPara = cmdBase + $" -p {i}";
  1731. }
  1732. else
  1733. {
  1734. cmdPara = cmdBase + $" -p {playerIp[i]}";
  1735. }
  1736. if (saveDebugLog)
  1737. {
  1738. cmdPara = cmdPara + " -d";
  1739. }
  1740. if (showDebugLog)
  1741. {
  1742. cmdPara = cmdPara + " -o";
  1743. }
  1744. if (warningOnly)
  1745. {
  1746. cmdPara = cmdPara + " -w";
  1747. }
  1748. RunCmd(cmdExe, cmdPara);
  1749. }
  1750. if (trickerCount != 0)
  1751. {
  1752. string cmdPara;
  1753. if (filePath == null)
  1754. {
  1755. cmdBase = $" {Data.FilePath}\\THUAI6\\win\\CAPI\\python\\PyAPI\\main.py -I {IP} -P {port} ";
  1756. }
  1757. else
  1758. {
  1759. cmdBase = " " + filePath[studentCount] + $" -I {IP} -P {port} ";
  1760. }
  1761. cmdPara = cmdBase + " -p 4";
  1762. if (saveDebugLog)
  1763. {
  1764. cmdPara = cmdPara + " -d";
  1765. }
  1766. if (showDebugLog)
  1767. {
  1768. cmdPara = cmdPara + " -o";
  1769. }
  1770. if (warningOnly)
  1771. {
  1772. cmdPara = cmdPara + " -w";
  1773. }
  1774. RunCmd(cmdExe, cmdPara);
  1775. }
  1776. return 0;
  1777. }
  1778. }
  1779. }
  1780. }
  1781. namespace WebConnect
  1782. {
  1783. class Web
  1784. {
  1785. public enum language { cpp, py };
  1786. public static string logintoken = "";
  1787. async public Task<int> LoginToEEsast(HttpClient client, string useremail, string password)
  1788. {
  1789. string token = "";
  1790. try
  1791. {
  1792. using (var response = await client.PostAsync("https://api.eesast.com/users/login", JsonContent.Create(new
  1793. {
  1794. email = useremail,
  1795. password = password,
  1796. })))
  1797. {
  1798. switch (response.StatusCode)
  1799. {
  1800. case System.Net.HttpStatusCode.OK:
  1801. //Console.WriteLine("Success login");
  1802. token = (System.Text.Json.JsonSerializer.Deserialize(await response.Content.ReadAsStreamAsync(), typeof(LoginResponse), new JsonSerializerOptions()
  1803. {
  1804. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  1805. }) as LoginResponse)
  1806. ?.Token ??
  1807. throw new Exception("no token!");
  1808. logintoken = token;
  1809. SaveToken();
  1810. var info = Utils.DeserializeJson1<Dictionary<string, string>>(await response.Content.ReadAsStringAsync());
  1811. Downloader.UserInfo._id = info["_id"];
  1812. Downloader.UserInfo.email = info["email"];
  1813. break;
  1814. default:
  1815. int code = ((int)response.StatusCode);
  1816. //Console.WriteLine(code);
  1817. if (code == 401)
  1818. {
  1819. //Console.WriteLine("邮箱或密码错误!");
  1820. return -1;
  1821. }
  1822. break;
  1823. }
  1824. return 0;
  1825. }
  1826. }
  1827. catch
  1828. {
  1829. return -2;
  1830. }
  1831. }
  1832. /// <summary>
  1833. ///
  1834. /// </summary>
  1835. /// <param name="client">http client</param>
  1836. /// <param name="tarfile">代码源位置</param>
  1837. /// <param name="type">编程语言,格式为"cpp"或"python"</param>
  1838. /// <param name="plr">第x位玩家,格式为"player_x"</param>
  1839. /// <returns>-1:tokenFail;-2:FileNotExist;-3:CosFail;-4:loginTimeout;-5:Fail;-6:ReadFileFail;-7:networkError</returns>
  1840. async public Task<int> UploadFiles(HttpClient client, string tarfile, string type, string plr) //用来上传文件
  1841. {
  1842. if (!ReadToken()) //读取token失败
  1843. {
  1844. return -1;
  1845. }
  1846. try
  1847. {
  1848. string content;
  1849. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1850. if (!File.Exists(tarfile))
  1851. {
  1852. //Console.WriteLine("文件不存在!");
  1853. return -2;
  1854. }
  1855. using FileStream fs = new FileStream(tarfile, FileMode.Open, FileAccess.Read);
  1856. using StreamReader sr = new StreamReader(fs);
  1857. content = sr.ReadToEnd();
  1858. string targetUrl = $"https://api.eesast.com/static/player?team_id={await GetTeamId()}";
  1859. using (var response = await client.GetAsync(targetUrl))
  1860. {
  1861. switch (response.StatusCode)
  1862. {
  1863. case System.Net.HttpStatusCode.OK:
  1864. var res = Utils.DeserializeJson1<Dictionary<string, string>>(await response.Content.ReadAsStringAsync());
  1865. string appid = "1255334966"; // 设置腾讯云账户的账户标识(APPID)
  1866. string region = "ap-beijing"; // 设置一个默认的存储桶地域
  1867. CosXmlConfig config = new CosXmlConfig.Builder()
  1868. .IsHttps(true) // 设置默认 HTTPS 请求
  1869. .SetAppid(appid) // 设置腾讯云账户的账户标识 APPID
  1870. .SetRegion(region) // 设置一个默认的存储桶地域
  1871. .SetDebugLog(true) // 显示日志
  1872. .Build(); // 创建 CosXmlConfig 对象
  1873. string tmpSecretId = res["TmpSecretId"]; //"临时密钥 SecretId";
  1874. string tmpSecretKey = res["TmpSecretKey"]; //"临时密钥 SecretKey";
  1875. string tmpToken = res["SecurityToken"]; //"临时密钥 token";
  1876. long tmpExpiredTime = Convert.ToInt64(res["ExpiredTime"]); //临时密钥有效截止时间,精确到秒
  1877. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  1878. tmpSecretId, tmpSecretKey, tmpExpiredTime, tmpToken
  1879. );
  1880. // 初始化 CosXmlServer
  1881. CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);
  1882. // 初始化 TransferConfig
  1883. TransferConfig transferConfig = new TransferConfig();
  1884. // 初始化 TransferManager
  1885. TransferManager transferManager = new TransferManager(cosXml, transferConfig);
  1886. string bucket = "eesast-1255334966"; //存储桶,格式:BucketName-APPID
  1887. string cosPath = $"/THUAI6/{GetTeamId()}/{type}/{plr}"; //对象在存储桶中的位置标识符,即称对象键
  1888. string srcPath = tarfile;//本地文件绝对路径
  1889. // 上传对象
  1890. COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);
  1891. uploadTask.SetSrcPath(srcPath);
  1892. uploadTask.progressCallback = delegate (long completed, long total)
  1893. {
  1894. //Console.WriteLine(string.Format("progress = {0:##.##}%", completed * 100.0 / total));
  1895. };
  1896. try
  1897. {
  1898. COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask);
  1899. //Console.WriteLine(result.GetResultInfo());
  1900. string eTag = result.eTag;
  1901. //到这里应该是成功了,但是因为我没有试过,也不知道具体情况,可能还要根据result的内容判断
  1902. }
  1903. catch (Exception)
  1904. {
  1905. return -3;
  1906. }
  1907. break;
  1908. case System.Net.HttpStatusCode.Unauthorized:
  1909. //Console.WriteLine("您未登录或登录过期,请先登录");
  1910. return -4;
  1911. default:
  1912. //Console.WriteLine("上传失败!");
  1913. return -5;
  1914. }
  1915. }
  1916. }
  1917. catch (IOException)
  1918. {
  1919. //Console.WriteLine("文件读取错误!请检查文件是否被其它应用占用!");
  1920. return -6;
  1921. }
  1922. catch
  1923. {
  1924. //Console.WriteLine("请求错误!请检查网络连接!");
  1925. return -7;
  1926. }
  1927. return 0;
  1928. }
  1929. async public Task UserDetails(HttpClient client) // 用来测试访问网站
  1930. {
  1931. if (!ReadToken()) // 读取token失败
  1932. {
  1933. return;
  1934. }
  1935. try
  1936. {
  1937. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1938. Console.WriteLine(logintoken);
  1939. using (var response = await client.GetAsync("https://api.eesast.com/application/info")) // JsonContent.Create(new
  1940. //{
  1941. //})))
  1942. {
  1943. switch (response.StatusCode)
  1944. {
  1945. case System.Net.HttpStatusCode.OK:
  1946. Console.WriteLine("Require OK");
  1947. Console.WriteLine(await response.Content.ReadAsStringAsync());
  1948. break;
  1949. default:
  1950. int code = ((int)response.StatusCode);
  1951. if (code == 401)
  1952. {
  1953. Console.WriteLine("您未登录或登录过期,请先登录");
  1954. }
  1955. return;
  1956. }
  1957. }
  1958. }
  1959. catch
  1960. {
  1961. Console.WriteLine("请求错误!请检查网络连接!");
  1962. }
  1963. }
  1964. public void SaveToken() // 保存token
  1965. {
  1966. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1967. try
  1968. {
  1969. string json;
  1970. Dictionary<string, string> dict = new Dictionary<string, string>();
  1971. using FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1972. using (StreamReader r = new StreamReader(fs))
  1973. {
  1974. json = r.ReadToEnd();
  1975. if (json == null || json == "")
  1976. {
  1977. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1978. }
  1979. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  1980. if (dict.ContainsKey("token"))
  1981. {
  1982. dict.Remove("token");
  1983. }
  1984. dict.Add("token", logintoken);
  1985. }
  1986. using FileStream fs2 = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1987. using StreamWriter sw = new StreamWriter(fs2);
  1988. fs2.SetLength(0);
  1989. sw.Write(JsonConvert.SerializeObject(dict)); //将token写入文件
  1990. }
  1991. catch (DirectoryNotFoundException)
  1992. {
  1993. Console.WriteLine("保存token时未找到下载器地址!请检查下载器是否被移动!");
  1994. }
  1995. catch (PathTooLongException)
  1996. {
  1997. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1998. }
  1999. catch (ArgumentNullException)
  2000. {
  2001. Console.WriteLine("下载器路径初始化失败!");
  2002. }
  2003. catch (IOException)
  2004. {
  2005. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  2006. }
  2007. }
  2008. public static int WriteJson(string key, string data)
  2009. {
  2010. try
  2011. {
  2012. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  2013. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  2014. StreamReader sr = new StreamReader(fs);
  2015. string json = sr.ReadToEnd();
  2016. if (json == null || json == "")
  2017. {
  2018. json += @"{""THUAI6""" + ":" + @"""2023""}";
  2019. }
  2020. Dictionary<string, string> dict = new Dictionary<string, string>();
  2021. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  2022. if (!dict.ContainsKey(key))
  2023. {
  2024. dict.Add(key, data);
  2025. }
  2026. else
  2027. {
  2028. dict[key] = data;
  2029. }
  2030. sr.Close();
  2031. fs.Close();
  2032. FileStream fs2 = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  2033. StreamWriter sw = new StreamWriter(fs2);
  2034. sw.WriteLine(JsonConvert.SerializeObject(dict));
  2035. sw.Close();
  2036. fs2.Close();
  2037. return 0;//成功
  2038. }
  2039. catch
  2040. {
  2041. return -1;//失败
  2042. }
  2043. }
  2044. public static string? ReadJson(string key)
  2045. {
  2046. try
  2047. {
  2048. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  2049. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  2050. StreamReader sr = new StreamReader(fs);
  2051. string json = sr.ReadToEnd();
  2052. Dictionary<string, string> dict = new Dictionary<string, string>();
  2053. if (json == null || json == "")
  2054. {
  2055. json += @"{""THUAI6""" + ":" + @"""2023""}";
  2056. }
  2057. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  2058. fs.Close();
  2059. sr.Close();
  2060. return dict[key];
  2061. }
  2062. catch
  2063. {
  2064. return null; //文件不存在或者已被占用
  2065. }
  2066. }
  2067. public bool ReadToken() // 读取token
  2068. {
  2069. try
  2070. {
  2071. string json;
  2072. Dictionary<string, string> dict = new Dictionary<string, string>();
  2073. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  2074. using FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  2075. using StreamReader sr = new StreamReader(fs);
  2076. json = sr.ReadToEnd();
  2077. if (json == null || json == "")
  2078. {
  2079. json += @"{""THUAI6""" + ":" + @"""2023""}";
  2080. }
  2081. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  2082. if (!dict.ContainsKey("token"))
  2083. {
  2084. return false;
  2085. }
  2086. else
  2087. {
  2088. logintoken = dict["token"];
  2089. return true;
  2090. }
  2091. }
  2092. catch (DirectoryNotFoundException)
  2093. {
  2094. Console.WriteLine("读取token时未找到下载器地址!请检查下载器是否被移动!");
  2095. return false;
  2096. }
  2097. catch (FileNotFoundException)
  2098. {
  2099. //没有登陆
  2100. Console.WriteLine("请先登录!");
  2101. return false;
  2102. }
  2103. catch (PathTooLongException)
  2104. {
  2105. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  2106. return false;
  2107. }
  2108. catch (ArgumentNullException)
  2109. {
  2110. Console.WriteLine("下载器路径初始化失败!");
  2111. return false;
  2112. }
  2113. catch (IOException)
  2114. {
  2115. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  2116. return false;
  2117. }
  2118. }
  2119. async public Task<string> GetTeamId()
  2120. {
  2121. var client = new HttpClient();
  2122. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  2123. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  2124. //var content = new StringContent($@"
  2125. // {{
  2126. // ""query"": ""query MyQuery {{contest_team_member(where: {{user_id: {{_eq: \""{Downloader.UserInfo._id}\""}}}}) {{ team_id }}}}"",
  2127. // ""variables"": {{}},
  2128. // }}", null, "application/json");
  2129. 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");
  2130. request.Content = content;
  2131. var response = await client.SendAsync(request);
  2132. response.EnsureSuccessStatusCode();
  2133. var info = await response.Content.ReadAsStringAsync();
  2134. var s1 = Utils.DeserializeJson1<Dictionary<string, object>>(info)["data"];
  2135. var s2 = Utils.DeserializeJson1<Dictionary<string, List<object>>>(s1.ToString() ?? "")["contest_team_member"];
  2136. var sres = Utils.DeserializeJson1<Dictionary<string, string>>(s2[0].ToString() ?? "")["team_id"];
  2137. return sres;
  2138. }
  2139. async public Task<string> GetUserId(string learnNumber)
  2140. {
  2141. var client = new HttpClient();
  2142. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  2143. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  2144. var content = new StringContent("{\"query\":\"query MyQuery {\r\n user(where: {id: {_eq: \""
  2145. + learnNumber + "\"}}) {\r\n _id\r\n }\r\n}\r\n\",\"variables\":{}}", null, "application/json");
  2146. request.Content = content;
  2147. var response = await client.SendAsync(request);
  2148. response.EnsureSuccessStatusCode();
  2149. return await response.Content.ReadAsStringAsync();
  2150. }
  2151. }
  2152. [Serializable]
  2153. record LoginResponse
  2154. {
  2155. // Map `Token` to `token` when serializing
  2156. public string Token { get; set; } = "";
  2157. }
  2158. internal static class Utils
  2159. {
  2160. public static T DeserializeJson1<T>(string json)
  2161. where T : notnull
  2162. {
  2163. return JsonConvert.DeserializeObject<T>(json)
  2164. ?? throw new Exception("Failed to deserialize json.");
  2165. }
  2166. public static T? TryDeserializeJson<T>(string json)
  2167. where T : notnull
  2168. {
  2169. return JsonConvert.DeserializeObject<T>(json);
  2170. }
  2171. }
  2172. }