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 102 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264
  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, updateFile = 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. public class RunInfo //UI需要在调用Launch函数前保证其中数据已经更新并有效
  1518. {
  1519. static public RunMode mode;
  1520. static public string? IP;
  1521. static public int port;
  1522. static public int studentCount;
  1523. static public int trickerCount;
  1524. static public int gameTimeSec;
  1525. static public string? playbackFileName;
  1526. static public int characterID;
  1527. static public int type;
  1528. static public bool saveDebugLog;
  1529. static public bool showDebugLog;
  1530. static public bool warningOnly;
  1531. static public bool visiting;
  1532. static public int occupation;
  1533. static public List<int>? playerId = new List<int>(); //两者长度必须与studentCount + trickerCount一致
  1534. static public List<string>? filePath = new List<string>();
  1535. }
  1536. /// <summary>
  1537. /// 运行cmd命令
  1538. /// 会显示命令窗口
  1539. /// </summary>
  1540. /// <param name="cmdExe">指定应用程序的完整路径</param>
  1541. /// <param name="cmdStr">执行命令行参数</param>
  1542. static bool RunCmd(string cmdExe, string cmdStr)
  1543. {
  1544. bool result = false;
  1545. try
  1546. {
  1547. using (Process myPro = new Process())
  1548. {
  1549. //指定启动进程是调用的应用程序和命令行参数
  1550. ProcessStartInfo psi = new ProcessStartInfo(cmdExe, cmdStr);
  1551. myPro.StartInfo = psi;
  1552. myPro.Start();
  1553. //myPro.WaitForExitAsync();
  1554. result = true;
  1555. }
  1556. }
  1557. catch
  1558. {
  1559. }
  1560. return result;
  1561. }
  1562. /// <summary>
  1563. /// 启动Server
  1564. /// 会显示命令窗口
  1565. /// </summary>
  1566. /// <param name="IP">指定Server运行的IPV4地址</param>
  1567. /// <param name="port">指定Server运行的端口</param>
  1568. /// <param name="studentCount">指定学生人数</param>
  1569. /// <param name="trickerCount">指定捣蛋鬼人数</param>
  1570. /// <param name="gameTimeSec">指定游戏最大时长</param>
  1571. /// <param name="playbackFileName">指定回放文件名称</param>
  1572. public static int StartServer(string? IP, int port, int studentCount, int trickerCount, int gameTimeSec, string? playbackFileName)
  1573. {
  1574. if (System.Diagnostics.Process.GetProcessesByName("Server").ToList().Count > 0)
  1575. {
  1576. System.Diagnostics.Process.GetProcessesByName("Server")[0].Kill();
  1577. }
  1578. string cmdExe = $"{Data.FilePath}\\THUAI6\\win\\win64\\Server.exe";
  1579. string cmdPara = $"--ip {IP} --port {port} --studentCount {studentCount} --trickerCount {trickerCount}" +
  1580. $" --gameTimeInSecond {gameTimeSec} --fileName {playbackFileName}";
  1581. RunCmd(cmdExe, cmdPara);
  1582. return 0;
  1583. }
  1584. /// <summary>
  1585. /// 启动Debug用的Server
  1586. /// 会显示命令窗口
  1587. /// </summary>
  1588. /// <param name="IP">指定Server运行的IPV4地址</param>
  1589. /// <param name="port">指定Server运行的端口</param>
  1590. /// <param name="studentCount">指定学生人数</param>
  1591. /// <param name="trickerCount">指定捣蛋鬼人数</param>
  1592. /// <param name="gameTimeSec">指定游戏最大时长</param>
  1593. /// <param name="playbackFileName">指定回放文件名称</param>
  1594. public static int StartServerForDebug(string? IP, int port, int studentCount, int trickerCount, int gameTimeSec, string? playbackFileName)
  1595. {
  1596. if (System.Diagnostics.Process.GetProcessesByName("Server").ToList().Count > 0)
  1597. {
  1598. System.Diagnostics.Process.GetProcessesByName("Server")[0].Kill();
  1599. }
  1600. string cmdExe = $"{Data.FilePath}\\THUAI6\\win\\win64\\Debug\\Server.exe";
  1601. string cmdPara = $"--ip {IP} --port {port} --studentCount {studentCount} --trickerCount {trickerCount} " +
  1602. $"--gameTimeInSecond {gameTimeSec} --fileName {playbackFileName}";
  1603. RunCmd(cmdExe, cmdPara);
  1604. return 0;
  1605. }
  1606. /// <summary>
  1607. /// 启动cpp,在这之前要先启动Server,可能还需要一些延时
  1608. /// 会显示命令窗口
  1609. /// </summary>
  1610. /// <param name="IP">指定Server运行的IPV4地址</param>
  1611. /// <param name="port">指定Server运行的端口</param>
  1612. /// <param name="studentCount">指定学生人数</param>
  1613. /// <param name="trickerCount">指定捣蛋鬼人数</param>
  1614. /// <param name="saveDebugLog">是否保存Debug日志文件</param>
  1615. /// <param name="showDebugLog">是否将日志输出到屏幕上</param>
  1616. /// <param name="warningOnly">在showDebugLog == true时,是否只输出警告或者报错(不影响日志保存)</param>
  1617. /// <param name="playerIp">默认为空,如果不为空,playerIp将会按照顺序代替默认从0~3的IP</param>
  1618. public static int RunCpp(string? IP, int port, int studentCount, int trickerCount, bool saveDebugLog,
  1619. bool showDebugLog, bool warningOnly, List<int>? playerIp = null, List<string>? filePath = null)
  1620. {
  1621. string cmdExe;
  1622. string cmdBase = $"-I {IP} -P {port} ";
  1623. for (int i = 0; i < studentCount; i++)
  1624. {
  1625. string cmdPara;
  1626. if (playerIp == null)
  1627. {
  1628. cmdPara = cmdBase + $" -p {i}";
  1629. }
  1630. else
  1631. {
  1632. cmdPara = cmdBase + $" -p {playerIp[i]}";
  1633. }
  1634. if (saveDebugLog)
  1635. {
  1636. cmdPara = cmdPara + " -d";
  1637. }
  1638. if (showDebugLog)
  1639. {
  1640. cmdPara = cmdPara + " -o";
  1641. }
  1642. if (warningOnly)
  1643. {
  1644. cmdPara = cmdPara + " -w";
  1645. }
  1646. if (filePath == null)
  1647. {
  1648. cmdExe = $"{Data.FilePath}\\THUAI6\\win\\CAPI\\cpp\\x64\\Debug\\API.exe";
  1649. }
  1650. else
  1651. {
  1652. cmdExe = filePath[i];
  1653. }
  1654. RunCmd(cmdExe, cmdPara);
  1655. }
  1656. if (trickerCount != 0)
  1657. {
  1658. string cmdPara;
  1659. cmdPara = cmdBase + " -p 4";
  1660. if (saveDebugLog)
  1661. {
  1662. cmdPara = cmdPara + " -d";
  1663. }
  1664. if (showDebugLog)
  1665. {
  1666. cmdPara = cmdPara + " -o";
  1667. }
  1668. if (warningOnly)
  1669. {
  1670. cmdPara = cmdPara + " -w";
  1671. }
  1672. if (filePath == null)
  1673. {
  1674. cmdExe = $"{Data.FilePath}\\THUAI6\\win\\CAPI\\cpp\\x64\\Debug\\API.exe";
  1675. }
  1676. else
  1677. {
  1678. cmdExe = filePath[studentCount];
  1679. }
  1680. RunCmd(cmdExe, cmdPara);
  1681. }
  1682. return 0;
  1683. }
  1684. /// <summary>
  1685. /// 启动客户端
  1686. /// 会显示命令窗口
  1687. /// </summary>
  1688. /// <param name="IP">指定Server运行的IPV4地址</param>
  1689. /// <param name="port">指定Server运行的端口</param>
  1690. /// <param name="characterID">进入游戏时的角色ID 0~4,0~3为学生,4为捣蛋鬼</param>
  1691. /// <param name="visiting">是否观战,当值为true时,characterID无效</param>
  1692. /// <param name="occupation">指定参加游戏时的角色职业,详情见说明文档</param>
  1693. /// <param name="type">角色类别,type = 1 表示学生,type = 2 表示捣蛋鬼</param>
  1694. public static int RunGUIClient(string? IP, int port, int characterID, bool visiting, int occupation = 1, int type = 1)
  1695. {
  1696. string cmdExe = $"{Data.FilePath}\\THUAI6\\win\\win64\\Client.exe";
  1697. string cmdBase = $"--port {port} --ip {IP} --type {type} --occupation {occupation}";
  1698. if (visiting)
  1699. {
  1700. cmdBase = cmdBase + " --characterID 200000";
  1701. }
  1702. else
  1703. {
  1704. cmdBase = cmdBase + $" --characterID {characterID}";
  1705. }
  1706. cmdBase = cmdBase + " --cl";
  1707. RunCmd(cmdExe, cmdBase);
  1708. return 0;
  1709. }
  1710. //启动python,参数同RunCpp
  1711. public static int RunPython(string? IP, int port, int studentCount, int trickerCount, bool saveDebugLog,
  1712. bool showDebugLog, bool warningOnly, List<int>? playerIp = null, List<string>? filePath = null)
  1713. {
  1714. string cmdExe = $"python";
  1715. string cmdBase;
  1716. for (int i = 0; i < studentCount; i++)
  1717. {
  1718. string cmdPara;
  1719. if (filePath == null)
  1720. {
  1721. cmdBase = $" {Data.FilePath}\\THUAI6\\win\\CAPI\\python\\PyAPI\\main.py -I {IP} -P {port} ";
  1722. }
  1723. else
  1724. {
  1725. cmdBase = " " + filePath[i] + $" -I {IP} -P {port} ";
  1726. }
  1727. if (playerIp == null)
  1728. {
  1729. cmdPara = cmdBase + $" -p {i}";
  1730. }
  1731. else
  1732. {
  1733. cmdPara = cmdBase + $" -p {playerIp[i]}";
  1734. }
  1735. if (saveDebugLog)
  1736. {
  1737. cmdPara = cmdPara + " -d";
  1738. }
  1739. if (showDebugLog)
  1740. {
  1741. cmdPara = cmdPara + " -o";
  1742. }
  1743. if (warningOnly)
  1744. {
  1745. cmdPara = cmdPara + " -w";
  1746. }
  1747. RunCmd(cmdExe, cmdPara);
  1748. }
  1749. if (trickerCount != 0)
  1750. {
  1751. string cmdPara;
  1752. if (filePath == null)
  1753. {
  1754. cmdBase = $" {Data.FilePath}\\THUAI6\\win\\CAPI\\python\\PyAPI\\main.py -I {IP} -P {port} ";
  1755. }
  1756. else
  1757. {
  1758. cmdBase = " " + filePath[studentCount] + $" -I {IP} -P {port} ";
  1759. }
  1760. cmdPara = cmdBase + " -p 4";
  1761. if (saveDebugLog)
  1762. {
  1763. cmdPara = cmdPara + " -d";
  1764. }
  1765. if (showDebugLog)
  1766. {
  1767. cmdPara = cmdPara + " -o";
  1768. }
  1769. if (warningOnly)
  1770. {
  1771. cmdPara = cmdPara + " -w";
  1772. }
  1773. RunCmd(cmdExe, cmdPara);
  1774. }
  1775. return 0;
  1776. }
  1777. }
  1778. }
  1779. }
  1780. namespace WebConnect
  1781. {
  1782. class Web
  1783. {
  1784. public enum language { cpp, py };
  1785. public static string logintoken = "";
  1786. async public Task<int> LoginToEEsast(HttpClient client, string useremail, string password)
  1787. {
  1788. string token = "";
  1789. try
  1790. {
  1791. using (var response = await client.PostAsync("https://api.eesast.com/users/login", JsonContent.Create(new
  1792. {
  1793. email = useremail,
  1794. password = password,
  1795. })))
  1796. {
  1797. switch (response.StatusCode)
  1798. {
  1799. case System.Net.HttpStatusCode.OK:
  1800. //Console.WriteLine("Success login");
  1801. token = (System.Text.Json.JsonSerializer.Deserialize(await response.Content.ReadAsStreamAsync(), typeof(LoginResponse), new JsonSerializerOptions()
  1802. {
  1803. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  1804. }) as LoginResponse)
  1805. ?.Token ??
  1806. throw new Exception("no token!");
  1807. logintoken = token;
  1808. SaveToken();
  1809. var info = Utils.DeserializeJson1<Dictionary<string, string>>(await response.Content.ReadAsStringAsync());
  1810. Downloader.UserInfo._id = info["_id"];
  1811. Downloader.UserInfo.email = info["email"];
  1812. break;
  1813. default:
  1814. int code = ((int)response.StatusCode);
  1815. //Console.WriteLine(code);
  1816. if (code == 401)
  1817. {
  1818. //Console.WriteLine("邮箱或密码错误!");
  1819. return -1;
  1820. }
  1821. break;
  1822. }
  1823. return 0;
  1824. }
  1825. }
  1826. catch
  1827. {
  1828. return -2;
  1829. }
  1830. }
  1831. /// <summary>
  1832. ///
  1833. /// </summary>
  1834. /// <param name="client">http client</param>
  1835. /// <param name="tarfile">代码源位置</param>
  1836. /// <param name="type">编程语言,格式为"cpp"或"python"</param>
  1837. /// <param name="plr">第x位玩家,格式为"player_x"</param>
  1838. /// <returns>-1:tokenFail;-2:FileNotExist;-3:CosFail;-4:loginTimeout;-5:Fail;-6:ReadFileFail;-7:networkError</returns>
  1839. async public Task<int> UploadFiles(HttpClient client, string tarfile, string type, string plr) //用来上传文件
  1840. {
  1841. if (!ReadToken()) //读取token失败
  1842. {
  1843. return -1;
  1844. }
  1845. try
  1846. {
  1847. string content;
  1848. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1849. if (!File.Exists(tarfile))
  1850. {
  1851. //Console.WriteLine("文件不存在!");
  1852. return -2;
  1853. }
  1854. using FileStream fs = new FileStream(tarfile, FileMode.Open, FileAccess.Read);
  1855. using StreamReader sr = new StreamReader(fs);
  1856. content = sr.ReadToEnd();
  1857. string targetUrl = $"https://api.eesast.com/static/player?team_id={await GetTeamId()}";
  1858. using (var response = await client.GetAsync(targetUrl))
  1859. {
  1860. switch (response.StatusCode)
  1861. {
  1862. case System.Net.HttpStatusCode.OK:
  1863. var res = Utils.DeserializeJson1<Dictionary<string, string>>(await response.Content.ReadAsStringAsync());
  1864. string appid = "1255334966"; // 设置腾讯云账户的账户标识(APPID)
  1865. string region = "ap-beijing"; // 设置一个默认的存储桶地域
  1866. CosXmlConfig config = new CosXmlConfig.Builder()
  1867. .IsHttps(true) // 设置默认 HTTPS 请求
  1868. .SetAppid(appid) // 设置腾讯云账户的账户标识 APPID
  1869. .SetRegion(region) // 设置一个默认的存储桶地域
  1870. .SetDebugLog(true) // 显示日志
  1871. .Build(); // 创建 CosXmlConfig 对象
  1872. string tmpSecretId = res["TmpSecretId"]; //"临时密钥 SecretId";
  1873. string tmpSecretKey = res["TmpSecretKey"]; //"临时密钥 SecretKey";
  1874. string tmpToken = res["SecurityToken"]; //"临时密钥 token";
  1875. long tmpExpiredTime = Convert.ToInt64(res["ExpiredTime"]); //临时密钥有效截止时间,精确到秒
  1876. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  1877. tmpSecretId, tmpSecretKey, tmpExpiredTime, tmpToken
  1878. );
  1879. // 初始化 CosXmlServer
  1880. CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);
  1881. // 初始化 TransferConfig
  1882. TransferConfig transferConfig = new TransferConfig();
  1883. // 初始化 TransferManager
  1884. TransferManager transferManager = new TransferManager(cosXml, transferConfig);
  1885. string bucket = "eesast-1255334966"; //存储桶,格式:BucketName-APPID
  1886. string cosPath = $"/THUAI6/{GetTeamId()}/{type}/{plr}"; //对象在存储桶中的位置标识符,即称对象键
  1887. string srcPath = tarfile;//本地文件绝对路径
  1888. // 上传对象
  1889. COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);
  1890. uploadTask.SetSrcPath(srcPath);
  1891. uploadTask.progressCallback = delegate (long completed, long total)
  1892. {
  1893. //Console.WriteLine(string.Format("progress = {0:##.##}%", completed * 100.0 / total));
  1894. };
  1895. try
  1896. {
  1897. COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask);
  1898. //Console.WriteLine(result.GetResultInfo());
  1899. string eTag = result.eTag;
  1900. //到这里应该是成功了,但是因为我没有试过,也不知道具体情况,可能还要根据result的内容判断
  1901. }
  1902. catch (Exception)
  1903. {
  1904. return -3;
  1905. }
  1906. break;
  1907. case System.Net.HttpStatusCode.Unauthorized:
  1908. //Console.WriteLine("您未登录或登录过期,请先登录");
  1909. return -4;
  1910. default:
  1911. //Console.WriteLine("上传失败!");
  1912. return -5;
  1913. }
  1914. }
  1915. }
  1916. catch (IOException)
  1917. {
  1918. //Console.WriteLine("文件读取错误!请检查文件是否被其它应用占用!");
  1919. return -6;
  1920. }
  1921. catch
  1922. {
  1923. //Console.WriteLine("请求错误!请检查网络连接!");
  1924. return -7;
  1925. }
  1926. return 0;
  1927. }
  1928. async public Task UserDetails(HttpClient client) // 用来测试访问网站
  1929. {
  1930. if (!ReadToken()) // 读取token失败
  1931. {
  1932. return;
  1933. }
  1934. try
  1935. {
  1936. client.DefaultRequestHeaders.Authorization = new("Bearer", logintoken);
  1937. Console.WriteLine(logintoken);
  1938. using (var response = await client.GetAsync("https://api.eesast.com/application/info")) // JsonContent.Create(new
  1939. //{
  1940. //})))
  1941. {
  1942. switch (response.StatusCode)
  1943. {
  1944. case System.Net.HttpStatusCode.OK:
  1945. Console.WriteLine("Require OK");
  1946. Console.WriteLine(await response.Content.ReadAsStringAsync());
  1947. break;
  1948. default:
  1949. int code = ((int)response.StatusCode);
  1950. if (code == 401)
  1951. {
  1952. Console.WriteLine("您未登录或登录过期,请先登录");
  1953. }
  1954. return;
  1955. }
  1956. }
  1957. }
  1958. catch
  1959. {
  1960. Console.WriteLine("请求错误!请检查网络连接!");
  1961. }
  1962. }
  1963. public void SaveToken() // 保存token
  1964. {
  1965. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  1966. try
  1967. {
  1968. string json;
  1969. Dictionary<string, string> dict = new Dictionary<string, string>();
  1970. using FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1971. using (StreamReader r = new StreamReader(fs))
  1972. {
  1973. json = r.ReadToEnd();
  1974. if (json == null || json == "")
  1975. {
  1976. json += @"{""THUAI6""" + ":" + @"""2023""}";
  1977. }
  1978. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  1979. if (dict.ContainsKey("token"))
  1980. {
  1981. dict.Remove("token");
  1982. }
  1983. dict.Add("token", logintoken);
  1984. }
  1985. using FileStream fs2 = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  1986. using StreamWriter sw = new StreamWriter(fs2);
  1987. fs2.SetLength(0);
  1988. sw.Write(JsonConvert.SerializeObject(dict)); //将token写入文件
  1989. }
  1990. catch (DirectoryNotFoundException)
  1991. {
  1992. Console.WriteLine("保存token时未找到下载器地址!请检查下载器是否被移动!");
  1993. }
  1994. catch (PathTooLongException)
  1995. {
  1996. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  1997. }
  1998. catch (ArgumentNullException)
  1999. {
  2000. Console.WriteLine("下载器路径初始化失败!");
  2001. }
  2002. catch (IOException)
  2003. {
  2004. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  2005. }
  2006. }
  2007. public static int WriteJson(string key, string data)
  2008. {
  2009. try
  2010. {
  2011. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  2012. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  2013. StreamReader sr = new StreamReader(fs);
  2014. string json = sr.ReadToEnd();
  2015. if (json == null || json == "")
  2016. {
  2017. json += @"{""THUAI6""" + ":" + @"""2023""}";
  2018. }
  2019. Dictionary<string, string> dict = new Dictionary<string, string>();
  2020. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  2021. if (!dict.ContainsKey(key))
  2022. {
  2023. dict.Add(key, data);
  2024. }
  2025. else
  2026. {
  2027. dict[key] = data;
  2028. }
  2029. sr.Close();
  2030. fs.Close();
  2031. FileStream fs2 = new FileStream(savepath, FileMode.Open, FileAccess.ReadWrite);
  2032. StreamWriter sw = new StreamWriter(fs2);
  2033. sw.WriteLine(JsonConvert.SerializeObject(dict));
  2034. sw.Close();
  2035. fs2.Close();
  2036. return 0;//成功
  2037. }
  2038. catch
  2039. {
  2040. return -1;//失败
  2041. }
  2042. }
  2043. public static string? ReadJson(string key)
  2044. {
  2045. try
  2046. {
  2047. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  2048. FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  2049. StreamReader sr = new StreamReader(fs);
  2050. string json = sr.ReadToEnd();
  2051. Dictionary<string, string> dict = new Dictionary<string, string>();
  2052. if (json == null || json == "")
  2053. {
  2054. json += @"{""THUAI6""" + ":" + @"""2023""}";
  2055. }
  2056. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  2057. fs.Close();
  2058. sr.Close();
  2059. return dict[key];
  2060. }
  2061. catch
  2062. {
  2063. return null; //文件不存在或者已被占用
  2064. }
  2065. }
  2066. public bool ReadToken() // 读取token
  2067. {
  2068. try
  2069. {
  2070. string json;
  2071. Dictionary<string, string> dict = new Dictionary<string, string>();
  2072. string savepath = System.IO.Path.Combine(Data.dataPath, "THUAI6.json");
  2073. using FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
  2074. using StreamReader sr = new StreamReader(fs);
  2075. json = sr.ReadToEnd();
  2076. if (json == null || json == "")
  2077. {
  2078. json += @"{""THUAI6""" + ":" + @"""2023""}";
  2079. }
  2080. dict = Utils.DeserializeJson1<Dictionary<string, string>>(json);
  2081. if (!dict.ContainsKey("token"))
  2082. {
  2083. return false;
  2084. }
  2085. else
  2086. {
  2087. logintoken = dict["token"];
  2088. return true;
  2089. }
  2090. }
  2091. catch (DirectoryNotFoundException)
  2092. {
  2093. Console.WriteLine("读取token时未找到下载器地址!请检查下载器是否被移动!");
  2094. return false;
  2095. }
  2096. catch (FileNotFoundException)
  2097. {
  2098. //没有登陆
  2099. Console.WriteLine("请先登录!");
  2100. return false;
  2101. }
  2102. catch (PathTooLongException)
  2103. {
  2104. Console.WriteLine("下载器的路径名太长!请尝试移动下载器!");
  2105. return false;
  2106. }
  2107. catch (ArgumentNullException)
  2108. {
  2109. Console.WriteLine("下载器路径初始化失败!");
  2110. return false;
  2111. }
  2112. catch (IOException)
  2113. {
  2114. Console.WriteLine("写入token.dat发生冲突!请检查token.dat是否被其它程序占用!");
  2115. return false;
  2116. }
  2117. }
  2118. async public Task<string> GetTeamId()
  2119. {
  2120. var client = new HttpClient();
  2121. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  2122. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  2123. //var content = new StringContent($@"
  2124. // {{
  2125. // ""query"": ""query MyQuery {{contest_team_member(where: {{user_id: {{_eq: \""{Downloader.UserInfo._id}\""}}}}) {{ team_id }}}}"",
  2126. // ""variables"": {{}},
  2127. // }}", null, "application/json");
  2128. 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");
  2129. request.Content = content;
  2130. var response = await client.SendAsync(request);
  2131. response.EnsureSuccessStatusCode();
  2132. var info = await response.Content.ReadAsStringAsync();
  2133. var s1 = Utils.DeserializeJson1<Dictionary<string, object>>(info)["data"];
  2134. var s2 = Utils.DeserializeJson1<Dictionary<string, List<object>>>(s1.ToString() ?? "")["contest_team_member"];
  2135. var sres = Utils.DeserializeJson1<Dictionary<string, string>>(s2[0].ToString() ?? "")["team_id"];
  2136. return sres;
  2137. }
  2138. async public Task<string> GetUserId(string learnNumber)
  2139. {
  2140. var client = new HttpClient();
  2141. var request = new HttpRequestMessage(HttpMethod.Post, "https://api.eesast.com/dev/v1/graphql");
  2142. request.Headers.Add("x-hasura-admin-secret", "hasuraDevAdminSecret");
  2143. var content = new StringContent("{\"query\":\"query MyQuery {\r\n user(where: {id: {_eq: \""
  2144. + learnNumber + "\"}}) {\r\n _id\r\n }\r\n}\r\n\",\"variables\":{}}", null, "application/json");
  2145. request.Content = content;
  2146. var response = await client.SendAsync(request);
  2147. response.EnsureSuccessStatusCode();
  2148. return await response.Content.ReadAsStringAsync();
  2149. }
  2150. }
  2151. [Serializable]
  2152. record LoginResponse
  2153. {
  2154. // Map `Token` to `token` when serializing
  2155. public string Token { get; set; } = "";
  2156. }
  2157. internal static class Utils
  2158. {
  2159. public static T DeserializeJson1<T>(string json)
  2160. where T : notnull
  2161. {
  2162. return JsonConvert.DeserializeObject<T>(json)
  2163. ?? throw new Exception("Failed to deserialize json.");
  2164. }
  2165. public static T? TryDeserializeJson<T>(string json)
  2166. where T : notnull
  2167. {
  2168. return JsonConvert.DeserializeObject<T>(json);
  2169. }
  2170. }
  2171. }