public async Task InsertDSReplays() { List <DSReplay> replays = new List <DSReplay>(); lock (lockobject) { while (true) { DSReplay replay = null; DSReplays.TryTake(out replay); if (replay == null) { break; } else { replays.Add(replay); } } } if (replays.Any()) { await Task.Run(() => { DbDupFind.ScanRest(replays); }); } }
public static DSReplay GetDSReplay() { DSReplay replay = null; DSReplays.TryTake(out replay); return(replay); }
public static List <DSReplay> CheckDup(DSReplay rep, List <DSReplay> DSReplays) { List <DSReplay> RemoveReps = new List <DSReplay>(); var compreps = DSReplays.Where(x => x.GAMETIME > rep.GAMETIME.AddDays(-1) && x.GAMETIME <rep.GAMETIME.AddDays(1) && x.DURATION> rep.DURATION - TimeSpan.FromMinutes(1).TotalSeconds && x.DURATION < rep.DURATION + TimeSpan.FromMinutes(1).TotalSeconds ).ToList(); compreps.Remove(rep); List <string> Races = rep.DSPlayer.OrderBy(o => o.REALPOS).Select(s => s.RACE).ToList(); foreach (DSReplay crep in compreps) { List <string> compRaces = crep.DSPlayer.OrderBy(o => o.REALPOS).Select(s => s.RACE).ToList(); if (Races.SequenceEqual(compRaces)) { if (IsDup(rep, crep)) { RemoveReps.Add(MergeReps(rep, crep)); } } } return(RemoveReps); }
public static List <DSReplay> ReadJson(string file) { List <DSReplay> DSReplays = new List <DSReplay>(); HashSet <string> ReplayHash = new HashSet <string>(); string plhash = Path.GetFileNameWithoutExtension(file); Console.WriteLine("Working on " + plhash); if (File.Exists(file)) { foreach (string line in File.ReadAllLines(file)) { dsreplay rep = JsonSerializer.Deserialize <dsreplay>(line); if (ReplayHash.Contains(rep.REPLAY)) { continue; } DSReplay dsrep = Map.Rep(rep, plhash); ReplayHash.Add(rep.REPLAY); DSReplays.Add(dsrep); } } return(DSReplays); }
public static void FixWinner(DSReplay replay) { if (replay.WINNER < 0) { foreach (DSPlayer pl in replay.DSPlayer) { if (pl.RESULT == 1) { replay.WINNER = (sbyte)pl.TEAM; break; } } } foreach (DSPlayer pl in replay.DSPlayer) { if (pl.TEAM == replay.WINNER) { pl.RESULT = 1; } else { pl.RESULT = 2; } } }
public static int ScanAdd() { List <FileInfo> NewJsons = new List <FileInfo>(); foreach (var dir in Directory.GetDirectories(DSdata.ServerConfig.SumDir).Where(x => Path.GetFileName(x).Length == 64)) { foreach (var file in Directory.GetFiles(dir).Where(d => new FileInfo(d).LastWriteTime > DSdata.ServerConfig.LastRun).Select(s => new FileInfo(s))) { NewJsons.Add(file); } } if (!NewJsons.Any()) { Console.WriteLine("No new datafiles found."); return(0); } foreach (var file in NewJsons.OrderBy(o => o.LastWriteTime)) { ReadJson(file.FullName); } List <DSReplay> DSReplays = new List <DSReplay>(); foreach (dsreplay replay in sReplays) { DSReplay dsreplay = Map.Rep(replay); DSReplays.Add(dsreplay); } ScanRest(DSReplays); return(sReplays.Count); }
public static bool IsDup(DSReplay rep, DSReplay crep) { int isDupPossible = 0; if (rep.VERSION == crep.VERSION) { if (rep.MAXKILLSUM == crep.MAXKILLSUM) { isDupPossible++; } if (rep.MAXLEAVER == crep.MAXLEAVER) { isDupPossible++; } if (rep.MININCOME == crep.MININCOME) { isDupPossible++; } if (rep.MINARMY == crep.MINARMY) { isDupPossible++; } } else { int kdiff = Math.Abs(rep.MAXKILLSUM - crep.MAXKILLSUM); //int adiff = Math.Abs(rep.MINARMY - crep.MINARMY); int mdiff = Math.Abs(rep.MINKILLSUM - crep.MINKILLSUM); int ddiff = Math.Abs(rep.DURATION - crep.DURATION); if (ddiff == 0 || (kdiff < 1000 && mdiff < 1000)) { isDupPossible = 4; } } if (isDupPossible > 2) { TimeSpan t = rep.GAMETIME - crep.GAMETIME; if (t > MaxGametimeDiff) { MaxGametimeDiff = t; } TimeSpan d = TimeSpan.FromSeconds(Math.Abs(rep.DURATION - crep.DURATION)); if (d > MaxDurationDiff) { MaxDurationDiff = d; } return(true); } else { return(false); } }
public static void SaveReplay(DSReplayContext stcontext, DSReplay rep, bool bulk = false) { lock (stlockobject) { stcontext.DSReplays.Add(rep); if (bulk == false) { stcontext.SaveChanges(); } } }
public async Task PopulateDb() { _logger.LogInformation("Populating db"); await Task.Run(() => { while (arg.DbDone < arg.Total) { while (s2decode.DSReplays.Any()) { DSReplay rep = null; s2decode.DSReplays.TryTake(out rep); if (rep != null) { try { _db.SaveReplay(rep, true); } catch (Exception e) { _logger.LogError(e.Message); } finally { Interlocked.Increment(ref arg.DbDone); } } if (arg.DbDone % 10 == 0) { try { _db.SaveContext(); } catch (Exception e) { _logger.LogError(e.Message); } finally { DSdata.DesktopStatus.DatabaseReplays = arg.DbDone; } } } } try { _db.SaveContext(); } catch (Exception e) { _logger.LogError(e.Message); } finally { DSdata.DesktopStatus.DatabaseReplays = arg.DbDone; } _logger.LogInformation("Populating db finished."); }); }
public void CreateMiddleChart(DSReplay replay, ChartJS _chart) { List <string> labels = new List <string>(); List <double> midTeam1 = new List <double>(); List <double> midTeam2 = new List <double>(); TimeSpan gt = TimeSpan.FromSeconds(replay.DURATION) / 100; for (int i = 0; i < 100; i++) { TimeSpan gtint = gt * i; labels.Add(gtint.ToString(@"hh\:mm\:ss")); midTeam1.Add(replay.GetMiddle((int)(gtint.TotalSeconds * 22.4), 0) / 22.4); midTeam2.Add(replay.GetMiddle((int)(gtint.TotalSeconds * 22.4), 1) / 22.4); } _chart.data.labels = labels; ChartJSdataset dsTeam1 = new ChartJSdataset(); ChartJSdataset dsTeam2 = new ChartJSdataset(); dsTeam1.label = "Team1"; dsTeam1.fill = true; dsTeam1.pointRadius = 0; dsTeam1.pointHoverRadius = 6; dsTeam1.showLine = true; dsTeam1.borderWidth = 3; dsTeam2.label = "Team2"; dsTeam2.fill = true; dsTeam2.pointRadius = 0; dsTeam2.pointHoverRadius = 6; dsTeam2.showLine = true; dsTeam2.borderWidth = 3; var col = GetChartColor(replay.WINNER == 0); dsTeam1.backgroundColor.Add("rgba(0, 0, 0, 0)"); dsTeam1.borderColor = col.borderColor; dsTeam1.pointBackgroundColor = col.pointBackgroundColor; col = GetChartColor(replay.WINNER == 1); dsTeam2.backgroundColor.Add("rgba(0, 0, 0, 0)"); dsTeam2.borderColor = col.borderColor; dsTeam2.pointBackgroundColor = col.pointBackgroundColor; dsTeam1.data = midTeam1; dsTeam2.data = midTeam2; _chart.data.datasets.Add(dsTeam1); _chart.data.datasets.Add(dsTeam2); DrawChart(_chart); }
public static void FixPos(DSReplay replay) { foreach (DSPlayer pl in replay.DSPlayer) { if (pl.REALPOS == 0) { for (int j = 1; j <= 6; j++) { if (replay.PLAYERCOUNT == 2 && (j == 2 || j == 3 || j == 5 || j == 6)) { continue; } if (replay.PLAYERCOUNT == 4 && (j == 3 || j == 6)) { continue; } List <DSPlayer> temp = new List <DSPlayer>(replay.DSPlayer.Where(x => x.REALPOS == j).ToList()); if (temp.Count == 0) { pl.REALPOS = (byte)j; } } if (new List <DSPlayer>(replay.DSPlayer.Where(x => x.REALPOS == pl.POS).ToList()).Count == 0) { pl.REALPOS = pl.POS; } } if (new List <DSPlayer>(replay.DSPlayer.Where(x => x.REALPOS == pl.REALPOS).ToList()).Count > 1) { Console.WriteLine("Found double playerid for " + pl.POS + "|" + pl.REALPOS); for (int j = 1; j <= 6; j++) { if (replay.PLAYERCOUNT == 2 && (j == 2 || j == 3 || j == 5 || j == 6)) { continue; } if (replay.PLAYERCOUNT == 4 && (j == 3 || j == 6)) { continue; } if (new List <DSPlayer>(replay.DSPlayer.Where(x => x.REALPOS == j).ToList()).Count == 0) { pl.REALPOS = (byte)j; break; } } } } }
public void SaveReplay(DSReplay rep, bool bulk = false) { _logger.LogInformation("Saveing repls " + rep.REPLAYPATH); lock (lockobject) { DbReplays.Add(rep.REPLAYPATH); _context.DSReplays.Add(rep); if (bulk == false) { _context.SaveChanges(); } } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _options.Decoding = true; BulkInsertArgs arg = new BulkInsertArgs(); await Task.Run(() => { DateTime t = DateTime.UtcNow; var jsonfile = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\sc2dsstats_web\\data.json"; if (!File.Exists(jsonfile)) { return; } using (FileStream fs = File.OpenRead(jsonfile)) { arg.Total = CountLinesMaybe(fs); } using (var md5 = MD5.Create()) { foreach (var line in File.ReadAllLines(jsonfile)) { dsreplay rep = JsonSerializer.Deserialize <dsreplay>(line); if (rep != null) { rep.Init(); rep.GenHash(); string reppath = Status.ReplayFolder.Where(x => x.Value == rep.REPLAY.Substring(0, 47)).FirstOrDefault().Key; reppath += "/" + rep.REPLAY.Substring(48); reppath += ".SC2Replay"; rep.REPLAY = reppath; DSReplay Rep = Map.Rep(rep); _db.SaveReplay(Rep, true); arg.Count++; OnReplayProcessed(arg); } } } _db.SaveContext(); Console.WriteLine((DateTime.UtcNow - t).TotalSeconds); }); arg.Done = true; OnReplayProcessed(arg); _options.Decoding = false; }
public static DSReplay GetDetails(dynamic details) { DSReplay replay = new DSReplay() { DSPlayer = new HashSet <DSPlayer>() }; byte failsafe_pos = 0; foreach (var player in details["m_playerList"]) { if ((int)player["m_observe"] > 0) { continue; } failsafe_pos++; string name = DecodeService.GetString(player, "m_name"); Match m2 = rx_subname.Match(name); if (m2.Success) { name = m2.Groups[1].Value; } replay.DSPlayer.Add(new DSPlayer() { NAME = name, RACE = DecodeService.GetString(player, "m_race"), RESULT = (byte)(int)player["m_result"], TEAM = (byte)(int)player["m_teamId"], POS = failsafe_pos, WORKINGSETSLOT = player["m_workingSetSlotId"] != null ? (byte)(int)player["m_workingSetSlotId"] : (byte)0, Stats = new List <DbStats>(), Spawns = new List <DbSpawn>(), Refineries = new List <DbRefinery>(), Upgrades = new List <DbUpgrade>() }); } replay.PLAYERCOUNT = (byte)replay.DSPlayer.Count; long timeutc = (long)details["m_timeUTC"]; long georgian = timeutc; replay.GAMETIME = DateTime.FromFileTime(georgian); replay.GAMETIME = new DateTime(replay.GAMETIME.Year, replay.GAMETIME.Month, replay.GAMETIME.Day, replay.GAMETIME.Hour, replay.GAMETIME.Minute, replay.GAMETIME.Second, 0, replay.GAMETIME.Kind); return(replay); }
public static string GenHash(DSReplay replay) { string md5 = ""; string hashstring = ""; foreach (DSPlayer pl in replay.DSPlayer.OrderBy(o => o.POS)) { hashstring += pl.POS + pl.RACE; } hashstring += replay.MINARMY + replay.MINKILLSUM + replay.MININCOME + replay.MAXKILLSUM; using (MD5 md5Hash = MD5.Create()) { md5 = GetMd5Hash(md5Hash, hashstring); } return(md5); }
public static DSReplay MergeReps(DSReplay rep, DSReplay crep) { if (new Version(rep.VERSION) > new Version(crep.VERSION)) { foreach (var ent in crep.DSPlayer.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && rep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { rep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch (Exception e) { Console.WriteLine("???" + e.Message); } } return(crep); } else { foreach (var ent in rep.DSPlayer.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch (Exception e) { Console.WriteLine(":( " + e.Message); } } return(rep); } }
public static DSReplay DecodePython(Object stateInfo, bool toJson = true, bool GetDetails = false) { Interlocked.Increment(ref THREADS); DSReplay dsreplay = null; string rep = (string)stateInfo; //Console.WriteLine("Working on rep .."); string id = Path.GetFileNameWithoutExtension(rep); AddLog("Working on rep .. " + id); AddLog("Loading s2protocol .."); dynamic MPQArchive = SCOPE.GetVariable("MPQArchive"); dynamic archive = null; //dynamic files = null; dynamic contents = null; dynamic versions = null; try { archive = MPQArchive(rep); //files = archive.extract(); contents = archive.header["user_data_header"]["content"]; //versions = SCOPE.GetVariable("versions"); versions = SCOPE.GetVariable("versions"); } catch { AddLog("No MPQArchive for " + id); FailCleanup(rep, GetDetails); return(null); } dynamic header = null; try { lock (_locker) { header = versions.latest().decode_replay_header(contents); } } catch (Exception e) { AddLog("No header for " + id + ": " + e.Message + " " + versions.latest().ToString()); FailCleanup(rep, GetDetails); return(null); } if (header != null) { AddLog("Loading s2protocol header finished"); var baseBuild = header["m_version"]["m_baseBuild"]; dynamic protocol = null; try { protocol = versions.build(baseBuild); } catch { AddLog("No protocol found for " + id + " " + baseBuild.ToString()); FailCleanup(rep, GetDetails); return(null); } AddLog("Loading s2protocol protocol finished"); // init /** * var init_enc = archive.read_file("replay.initData"); * dynamic init_dec = null; * try * { * init_dec = protocol.decode_replay_initdata(init_enc); * } * catch * { * AddLog("No Init version for " + id); * FailCleanup(rep, GetDetails); * return null; * } * AddLog("Loading s2protocol init finished"); * * s2parse.GetInit(rep, init_dec); **/ // details var details_enc = archive.read_file("replay.details"); dynamic details_dec = null; try { details_dec = protocol.decode_replay_details(details_enc); } catch { AddLog("No Version for " + id); FailCleanup(rep, GetDetails); return(null); } AddLog("Loading s2protocol details finished"); //replay = DSparseNG.GetDetails(rep, details_dec); dsreplay = Details.Get(rep, details_dec); // trackerevents var trackerevents_enc = archive.read_file("replay.tracker.events"); dynamic trackerevents_dec = null; try { trackerevents_dec = protocol.decode_replay_tracker_events(trackerevents_enc); AddLog("Loading trackerevents success"); } catch { AddLog("No tracker version for " + id); FailCleanup(rep, GetDetails); return(null); } AddLog("Loading s2protocol trackerevents finished"); try { //replay = DSparseNG.GetTrackerevents(trackerevents_dec, replay, GetDetails); dsreplay = Trackerevents.Get(trackerevents_dec, dsreplay); } catch { AddLog("Trackerevents failed for " + id); FailCleanup(rep, GetDetails); return(null); } AddLog("trackerevents analyzed."); Initialize.Replay(dsreplay, GetDetails); if (toJson == true) { DSReplays.Add(dsreplay); } } Interlocked.Increment(ref DONE); Interlocked.Decrement(ref THREADS); return(null); }
public async Task <bool> GetAutoFile(string id, string myfile) { DSRestPlayer player = _context.DSRestPlayers.Include(p => p.Uploads).FirstOrDefault(f => f.Name == id); if (player == null) { return(false); } player.LastUpload = DateTime.UtcNow; string mypath = SharedDir + "/" + id; string mysum = SharedDir + "/sum/" + id + ".json"; if (!Directory.Exists(mypath)) { try { Directory.CreateDirectory(mypath); } catch (Exception e) { _logger.LogError("Could not create directory " + mypath + " " + e.Message); return(false); } } if (File.Exists(myfile)) { if (!File.Exists(mysum)) { File.Create(mysum).Dispose(); } string myjson = ""; return(await Task.Run(() => myjson = Decompress(new FileInfo(myfile), mypath, id, _logger)) .ContinueWith(task => { if (myjson == "") { return false; } if (File.Exists(myjson) && new FileInfo(myjson).Length > 0) { using (StreamWriter sw = File.AppendText(mysum)) { foreach (string line in File.ReadLines(myjson)) { if (!line.StartsWith(@"{")) { return false; } sw.WriteLine(line); dsreplay replay = null; try { replay = JsonSerializer.Deserialize <dsreplay>(line); if (replay != null) { DSReplay dsreplay = Map.Rep(replay); DSPlayer dsplayer = dsreplay.DSPlayer.FirstOrDefault(f => f.NAME == "player"); if (dsplayer != null) { dsplayer.NAME = id; } dsreplay.Upload = player.LastUpload; DSReplays.Add(dsreplay); player.Data++; } } catch (Exception e) { _logger.LogError("Could not Deserialize and map replay " + e.Message); } } } DSRestUpload upload = new DSRestUpload(); upload.Upload = player.LastUpload; upload.DSRestPlayer = player; _context.DSRestUploads.Add(upload); DSinfo info = Infos.FirstOrDefault(f => f.Key == id).Value; if (info != null) { DateTime LastRep = DateTime.MinValue; if (info.LastRep.Length == 14) { int year = int.Parse(info.LastRep.Substring(0, 4)); int month = int.Parse(info.LastRep.Substring(4, 2)); int day = int.Parse(info.LastRep.Substring(6, 2)); int hour = int.Parse(info.LastRep.Substring(8, 2)); int min = int.Parse(info.LastRep.Substring(10, 2)); int sec = int.Parse(info.LastRep.Substring(12, 2)); LastRep = new DateTime(year, month, day, hour, min, sec); } player.LastRep = LastRep; player.Json = info.Json; player.Total = info.Total; player.Version = info.Version; } lock (dblock) { _context.SaveChanges(); } InsertDSReplays(); return true; } else { return false; } })); } else { return(false); } }
public static List <DSReplay> InsertDSReplays(List <DSReplay> replays) { List <DSReplay> NewDbReps = new List <DSReplay>(); List <DSReplay> Dups = new List <DSReplay>(); using (var context = new DSReplayContext(Program._opt)) { var Replays = context.DSReplays.Include(p => p.DSPlayer); foreach (DSReplay replay in replays.ToArray()) { if (replay.MINARMY == 0 && replay.MINKILLSUM == 0 && replay.MAXKILLSUM == 0 && replay.DURATION < 120) { replays.Remove(replay); continue; } //DSReplay crep = context.DSReplays // .Include(p => p.DSPlayer) // .FirstOrDefault(s => s.HASH == replay.HASH); DSReplay crep = Replays.FirstOrDefault(s => s.HASH == replay.HASH); if (crep != null) { if (new Version(replay.VERSION) > new Version(crep.VERSION)) { foreach (var ent in crep.DSPlayer.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && replay.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { replay.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch (Exception e) { Program.logger.LogInformation($"Error in finding RealPos {e.Message}"); } } DBService.DeleteRep(context, crep.ID); } else { int i = 0; foreach (var ent in replay.DSPlayer.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { i++; crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch (Exception e) { Program.logger.LogInformation($"Error in finding RealPos {e.Message}"); } } if (i > 0) { context.SaveChanges(); } replays.Remove(replay); } } else { //Console.WriteLine("no dup"); } } int j = 0; foreach (DSReplay newdbrep in replays) { newdbrep.REPLAYPATH = ""; DBService.SaveReplay(context, newdbrep, true); NewDbReps.Add(newdbrep); j++; if (j % 100 == 0) { context.SaveChanges(); Program.logger.LogInformation($"{j}/{replays.Count}"); } } context.SaveChanges(); } return(NewDbReps); }
public static DSReplay Get(dynamic trackerevents_dec, DSReplay replay) { bool isBrawl_set = false; //bool noStagingAreaNextSpawn = true; bool noStagingAreaNextSpawn = false; if (replay.GAMETIME < new DateTime(2019, 03, 24, 21, 46, 15)) // 20190324214615 { noStagingAreaNextSpawn = true; } HashSet <string> Mutation = new HashSet <string>(); List <DbMiddle> Middle = new List <DbMiddle>(); Middle.Add(new DbMiddle(0, 0, replay)); replay.Middle = Middle; List <StagingAreaNextSpawn> stagingAreaNextSpawns = new List <StagingAreaNextSpawn>(); Vector2 ObjectivePlanetaryFortress = Vector2.Zero; Vector2 ObjectiveNexus = Vector2.Zero; Vector2 ObjectiveBunker = Vector2.Zero; Vector2 ObjectivePhotonCannon = Vector2.Zero; Vector2 Center = Vector2.Zero; KeyValuePair <Vector2, Vector2> LineT1 = new KeyValuePair <Vector2, Vector2>(Vector2.Zero, Vector2.Zero); KeyValuePair <Vector2, Vector2> LineT2 = new KeyValuePair <Vector2, Vector2>(Vector2.Zero, Vector2.Zero); int UnitID = 0; int LastSpawn = 480; int Winner = 0; foreach (PythonDictionary pydic in trackerevents_dec) { if (pydic.ContainsKey("m_unitTypeName")) //11998 { if (pydic.ContainsKey("m_controlPlayerId")) { int playerid = (int)pydic["m_controlPlayerId"]; int gameloop = (int)pydic["_gameloop"]; // Game end if (pydic["m_unitTypeName"].ToString().StartsWith("DeathBurst")) { replay.DURATION = (int)(gameloop / 22.4); if (playerid == 13) { replay.WINNER = 1; } else if (playerid == 14) { replay.WINNER = 0; } break; } // Objectives init if (gameloop == 0 && pydic.ContainsKey("m_creatorAbilityName") && (pydic["m_creatorAbilityName"] == null || pydic["m_creatorAbilityName"].ToString() == "")) { if (pydic["m_unitTypeName"].ToString() == "ObjectivePlanetaryFortress") { ObjectivePlanetaryFortress = new Vector2((int)pydic["m_x"], (int)pydic["m_y"]); } else if (pydic["m_unitTypeName"].ToString() == "ObjectiveNexus") { ObjectiveNexus = new Vector2((int)pydic["m_x"], (int)pydic["m_y"]); } else if (pydic["m_unitTypeName"].ToString() == "ObjectiveBunker") { ObjectiveBunker = new Vector2((int)pydic["m_x"], (int)pydic["m_y"]); } else if (pydic["m_unitTypeName"].ToString() == "ObjectivePhotonCannon") { ObjectivePhotonCannon = new Vector2((int)pydic["m_x"], (int)pydic["m_y"]); } if (ObjectiveBunker != Vector2.Zero && ObjectivePhotonCannon != Vector2.Zero && ObjectivePlanetaryFortress != Vector2.Zero && ObjectiveNexus != Vector2.Zero) { float x1t1 = ObjectivePlanetaryFortress.X + MathF.Cos(135 * MathF.PI / 180) * 100; float y1t1 = ObjectivePlanetaryFortress.Y + MathF.Sin(135 * MathF.PI / 180) * 100; float x2t1 = ObjectivePlanetaryFortress.X + MathF.Cos(315 * MathF.PI / 180) * 100; float y2t1 = ObjectivePlanetaryFortress.Y + MathF.Sin(315 * MathF.PI / 180) * 100; LineT1 = new KeyValuePair <Vector2, Vector2>(new Vector2(x1t1, y1t1), new Vector2(x2t1, y2t1)); float x1t2 = ObjectiveNexus.X + MathF.Cos(135 * MathF.PI / 180) * 100; float y1t2 = ObjectiveNexus.Y + MathF.Sin(135 * MathF.PI / 180) * 100; float x2t2 = ObjectiveNexus.X + MathF.Cos(315 * MathF.PI / 180) * 100; float y2t2 = ObjectiveNexus.Y + MathF.Sin(315 * MathF.PI / 180) * 100; LineT2 = new KeyValuePair <Vector2, Vector2>(new Vector2(x1t2, y1t2), new Vector2(x2t2, y2t2)); Center = new Vector2((ObjectiveNexus.X + ObjectivePlanetaryFortress.X) / 2, (ObjectiveNexus.Y + ObjectivePlanetaryFortress.Y) / 2); Objective obj = DSdata.Objectives.FirstOrDefault(x => x.Center == Center); if (obj == null) { obj = new Objective(); obj.Center = Center; obj.LineT1 = LineT1; obj.LineT2 = LineT2; obj.ObjectiveBunker = ObjectiveBunker; obj.ObjectiveNexus = ObjectiveNexus; obj.ObjectivePhotonCannon = ObjectivePhotonCannon; obj.ObjectivePlanetaryFortress = ObjectivePlanetaryFortress; DSdata.Objectives.Add(obj); obj.ID = DSdata.Objectives.Count; } replay.OBJECTIVE = obj.ID; } } if (playerid == 0 || playerid > 12) { continue; } // Player DSPlayer pl = replay.DSPlayer.SingleOrDefault(s => s.POS == playerid); if (pl == null) { pl = replay.DSPlayer.SingleOrDefault(s => s.WORKINGSETSLOT == playerid - 1); if (pl == null) { continue; } else { pl.POS = (byte)playerid; } } ; // Race if (gameloop < 1440) { Match m = rx_race2.Match(pydic["m_unitTypeName"].ToString()); if (m.Success && m.Groups[1].Value.Length > 0) { pl.RACE = m.Groups[1].Value; } } if (pydic.ContainsKey("m_creatorAbilityName")) { if (pydic["m_creatorAbilityName"] == null || pydic["m_creatorAbilityName"].ToString() == "") { if (gameloop == 0) { if (pydic["_event"].ToString() == "NNet.Replay.Tracker.SUnitBornEvent") { // Refineries init if (pydic["m_unitTypeName"].ToString().StartsWith("MineralField")) { int index = (int)pydic["m_unitTagIndex"]; int recycle = (int)pydic["m_unitTagRecycle"]; pl.Refineries.Add(new DbRefinery(gameloop, index, recycle, pl)); continue; } } } if (gameloop < 480) { continue; } if (noStagingAreaNextSpawn == false) { if (gameloop - LastSpawn >= 9) { continue; } } if (pydic["_event"].ToString() == "NNet.Replay.Tracker.SUnitBornEvent") { string born_unit = pydic["m_unitTypeName"].ToString(); bool isSpawnUnit = (born_unit switch { "TrophyRiftPremium" => true, "MineralIncome" => true, "ParasiticBombRelayDummy" => true, "Biomass" => true, "PurifierAdeptShade" => true, "PurifierTalisShade" => true, "HornerReaperLD9ClusterCharges" => true, "Broodling" => true, "Raptorling" => true, "InfestedLiberatorViralSwarm" => true, "SplitterlingSpawn" => true, "GuardianShell" => true, "BroodlingStetmann" => true, _ => false });
public static DSReplay Get(string replay_file, dynamic details_dec) { DSReplay replay = new DSReplay(); List <DSPlayer> Players = new List <DSPlayer>(); replay.REPLAYPATH = replay_file; int failsafe_pos = 0; foreach (var player in details_dec["m_playerList"]) { if (player["m_observe"] > 0) { continue; } failsafe_pos++; string name = ""; Bytes bab = null; try { bab = player["m_name"]; } catch { } if (bab != null) { name = Encoding.UTF8.GetString(bab.ToByteArray()); } else { name = player["m_name"].ToString(); } Match m2 = rx_subname.Match(name); if (m2.Success) { name = m2.Groups[1].Value; } DSPlayer pl = new DSPlayer(); pl.NAME = name; pl.RACE = player["m_race"].ToString(); pl.RESULT = byte.Parse(player["m_result"].ToString()); pl.TEAM = byte.Parse(player["m_teamId"].ToString()); pl.POS = (byte)failsafe_pos; if (player["m_workingSetSlotId"] != null) { pl.WORKINGSETSLOT = byte.Parse(player["m_workingSetSlotId"].ToString()); } pl.Stats = new List <DbStats>(); pl.Spawns = new List <DbSpawn>(); pl.Refineries = new List <DbRefinery>(); pl.Upgrades = new List <DbUpgrade>(); pl.DSReplay = replay; Players.Add(pl); } replay.PLAYERCOUNT = (byte)Players.Count; //long offset = (long)details_dec["m_timeLocalOffset"]; long timeutc = (long)details_dec["m_timeUTC"]; long georgian = timeutc; replay.GAMETIME = DateTime.FromFileTime(georgian); replay.GAMETIME = new DateTime(replay.GAMETIME.Year, replay.GAMETIME.Month, replay.GAMETIME.Day, replay.GAMETIME.Hour, replay.GAMETIME.Minute, replay.GAMETIME.Second, 0, replay.GAMETIME.Kind); replay.DSPlayer = Players; return(replay); }
// WebDatabase Replay // LocalDatabase Replay // DecodedReplay // OldReplay public static DSReplay Rep(dsreplay rep, string id = "player") { DSReplay dbrep = new DSReplay(); dbrep.REPLAYPATH = rep.REPLAY; using (var md5 = MD5.Create()) { string dirHash = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(Path.GetDirectoryName(rep.REPLAY)))).Replace("-", "").ToLowerInvariant(); string fileHash = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(Path.GetFileName(rep.REPLAY)))).Replace("-", "").ToLowerInvariant(); dbrep.REPLAY = dirHash + fileHash; } string gametime = rep.GAMETIME.ToString(); int year = int.Parse(gametime.Substring(0, 4)); int month = int.Parse(gametime.Substring(4, 2)); int day = int.Parse(gametime.Substring(6, 2)); int hour = int.Parse(gametime.Substring(8, 2)); int min = int.Parse(gametime.Substring(10, 2)); int sec = int.Parse(gametime.Substring(12, 2)); DateTime gtime = new DateTime(year, month, day, hour, min, sec); dbrep.GAMETIME = gtime; dbrep.WINNER = (sbyte)rep.WINNER; TimeSpan d = TimeSpan.FromSeconds(rep.DURATION / 22.4); dbrep.DURATION = (int)d.TotalSeconds; dbrep.MINKILLSUM = rep.MINKILLSUM; dbrep.MAXKILLSUM = rep.MAXKILLSUM; dbrep.MINARMY = rep.MINARMY; dbrep.MININCOME = (int)rep.MININCOME; dbrep.PLAYERCOUNT = (byte)rep.PLAYERCOUNT; dbrep.REPORTED = (byte)rep.REPORTED; dbrep.ISBRAWL = rep.ISBRAWL; dbrep.GAMEMODE = rep.GAMEMODE; dbrep.VERSION = rep.VERSION; dbrep.MAXLEAVER = 0; List <DSPlayer> pls = new List <DSPlayer>(); foreach (dsplayer pl in rep.PLAYERS) { DSPlayer dbpl = new DSPlayer(); dbpl.POS = (byte)pl.POS; dbpl.REALPOS = (byte)pl.REALPOS; if (pl.NAME == "player") { dbpl.NAME = id; } else { dbpl.NAME = pl.NAME; } dbpl.RACE = pl.RACE; if (pl.TEAM == rep.WINNER) { dbpl.WIN = true; } dbpl.TEAM = (byte)pl.TEAM; dbpl.KILLSUM = pl.KILLSUM; dbpl.INCOME = (int)pl.INCOME; dbpl.PDURATION = (int)TimeSpan.FromSeconds(pl.PDURATION / 22.4).TotalSeconds; dbpl.ARMY = pl.ARMY; dbpl.GAS = (byte)pl.GAS; dsplayer opp = rep.GetOpp(pl.REALPOS); if (opp != null) { dbpl.OPPRACE = opp.RACE; } int diff = dbrep.DURATION - dbpl.PDURATION; if (diff > dbrep.MAXLEAVER) { dbrep.MAXLEAVER = diff; } dbpl.DSReplay = dbrep; pls.Add(dbpl); List <DbBreakpoint> bps = new List <DbBreakpoint>(); foreach (var bp in pl.UNITS.Keys) { DbBreakpoint dbbp = new DbBreakpoint(); dbbp.Breakpoint = bp; dbbp.dsUnitsString = ""; foreach (var name in pl.UNITS[bp].Keys) { if (name == "Gas") { dbbp.Gas = pl.UNITS[bp][name]; } else if (name == "Upgrades") { dbbp.Upgrades = pl.UNITS[bp][name]; } else if (name == "Mid") { dbbp.Mid = pl.UNITS[bp][name]; } else { UnitModelBase unit = DSdata.Units.FirstOrDefault(f => f.Race == pl.RACE && f.Name == Fix.UnitName(name)); if (unit != null) { dbbp.dsUnitsString += unit.ID + "," + pl.UNITS[bp][name] + "|"; } else { dbbp.dsUnitsString += name + "," + pl.UNITS[bp][name] + "|"; } } } if (!String.IsNullOrEmpty(dbbp.dsUnitsString)) { dbbp.dsUnitsString = dbbp.dsUnitsString.Remove(dbbp.dsUnitsString.Length - 1); } bps.Add(dbbp); } dbpl.Breakpoints = bps; } dbrep.DSPlayer = pls as ICollection <DSPlayer>; dbrep.HASH = dbrep.GenHash(); dbrep.Upload = DateTime.UtcNow; return(dbrep); }
public static DSReplay Rep(Dsreplays rep) { DSReplay dbrep = new DSReplay(); dbrep.REPLAY = rep.Replay; dbrep.REPLAYPATH = String.Empty; dbrep.GAMETIME = rep.Gametime; dbrep.WINNER = (sbyte)rep.Winner; dbrep.DURATION = (int)rep.Duration; dbrep.MINKILLSUM = rep.Minkillsum; dbrep.MAXKILLSUM = rep.Maxkillsum; dbrep.MINARMY = rep.Minarmy; dbrep.MININCOME = (int)rep.Minincome; dbrep.PLAYERCOUNT = (byte)rep.Playercount; dbrep.REPORTED = (byte)rep.Reported; dbrep.ISBRAWL = rep.Isbrawl; dbrep.GAMEMODE = rep.Gamemode; dbrep.VERSION = rep.Version; dbrep.MAXLEAVER = 0; List <DSPlayer> pls = new List <DSPlayer>(); foreach (Dsplayers pl in rep.Dsplayers) { DSPlayer dbpl = new DSPlayer(); dbpl.POS = (byte)pl.Pos; dbpl.REALPOS = (byte)pl.Realpos; dbpl.NAME = pl.Name; dbpl.RACE = pl.Race; if (pl.Team == rep.Winner) { dbpl.WIN = true; } dbpl.TEAM = (byte)pl.Team; dbpl.KILLSUM = pl.Killsum; dbpl.INCOME = (int)pl.Income; dbpl.PDURATION = (int)pl.Pduration; dbpl.ARMY = pl.Army; dbpl.GAS = (byte)pl.Gas; Dsplayers opp = GetOpp(pl.Realpos, rep); if (opp != null) { dbpl.OPPRACE = opp.Race; } int diff = dbrep.DURATION - (int)pl.Pduration; if (diff > dbrep.MAXLEAVER) { dbrep.MAXLEAVER = diff; } dbpl.DSReplay = dbrep; pls.Add(dbpl); List <DbBreakpoint> bps = new List <DbBreakpoint>(); foreach (var bp in DSdata.s_breakpoints) { DbBreakpoint dbbp = new DbBreakpoint(); dbbp.Breakpoint = bp; dbbp.dsUnitsString = ""; foreach (var runit in pl.Dsunits.Where(x => x.Bp == bp)) { if (runit.Name == "Gas") { dbbp.Gas = runit.Count; } else if (runit.Name == "Upgrades") { dbbp.Upgrades = runit.Count; } else if (runit.Name == "Mid") { dbbp.Mid = runit.Count; } else { UnitModelBase unit = DSdata.Units.FirstOrDefault(f => f.Race == pl.Race && f.Name == Fix.UnitName(runit.Name)); if (unit != null) { dbbp.dsUnitsString += unit.ID + "," + runit.Count + "|"; } else { dbbp.dsUnitsString += runit.Name + "," + runit.Count + "|"; } } } if (!String.IsNullOrEmpty(dbbp.dsUnitsString)) { dbbp.dsUnitsString = dbbp.dsUnitsString.Remove(dbbp.dsUnitsString.Length - 1); } bps.Add(dbbp); } dbpl.Breakpoints = bps; } dbrep.DSPlayer = pls as ICollection <DSPlayer>; dbrep.HASH = dbrep.GenHash(); dbrep.Upload = DateTime.UtcNow; return(dbrep); }
public static HashSet <int> CheckDups(Dictionary <int, List <int> > CompareMe) { HashSet <int> DeleteMe = new HashSet <int>(); int i = 0; int c = CompareMe.Count; using (var context = new DSReplayContext(Program._opt)) { foreach (int id in CompareMe.Keys) { i++; if (i % 100 == 0) { Program.logger.LogInformation($"{i}/{c}"); } if (DeleteMe.Contains(id)) { continue; } DSReplay replay = context.DSReplays.First(s => s.ID == id); foreach (int cid in CompareMe[id]) { if (DeleteMe.Contains(cid)) { continue; } DSReplay crep = context.DSReplays.First(s => s.ID == cid); int isDupPossible = 0; if (replay.REPLAY == crep.REPLAY) { if (new Version(replay.VERSION) >= new Version(crep.VERSION)) { DeleteMe.Add(crep.ID); } else { DeleteMe.Add(replay.ID); } continue; } if (replay.VERSION == crep.VERSION) { if (replay.MAXKILLSUM == crep.MAXKILLSUM) { isDupPossible++; } if (replay.MAXLEAVER == crep.MAXLEAVER) { isDupPossible++; } if (replay.MININCOME == crep.MININCOME) { isDupPossible++; } if (replay.MINARMY == crep.MINARMY) { isDupPossible++; } } else { int kdiff = Math.Abs(replay.MAXKILLSUM - crep.MAXKILLSUM); //int adiff = Math.Abs(rep.MINARMY - crep.MINARMY); int mdiff = Math.Abs(replay.MINKILLSUM - crep.MINKILLSUM); int ddiff = Math.Abs(replay.DURATION - crep.DURATION); if (ddiff == 0 || (kdiff < 1000 && mdiff < 1000)) { isDupPossible = 4; } } if (isDupPossible > 2) { replay = context.DSReplays .Include(p => p.DSPlayer) .Single(s => s.ID == id); crep = context.DSReplays .Include(p => p.DSPlayer) .Single(s => s.ID == cid); if (new Version(replay.VERSION) > new Version(crep.VERSION)) { foreach (var ent in crep.DSPlayer.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && replay.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { replay.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch (Exception e) { Program.logger.LogInformation($"No RealPos Player found {e.Message}: {replay.ID}"); } } DeleteMe.Add(crep.ID); } else { foreach (var ent in replay.DSPlayer.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch (Exception e) { Program.logger.LogInformation($"No RealPos Player found {e.Message}: {crep.ID}"); } } DeleteMe.Add(replay.ID); } context.SaveChanges(); } } } } return(DeleteMe); }
public static List <DSReplay> InsertReplays() { List <DSReplay> NewDbReps = new List <DSReplay>(); List <DSReplay> Dups = new List <DSReplay>(); using (var context = new DSReplayContext(Program._opt)) { var Replays = context.DSReplays.Include(p => p.DSPlayer); foreach (dsreplay replay in sReplays.ToArray()) { //DSReplay crep = context.DSReplays // .Include(p => p.DSPlayer) // .FirstOrDefault(s => s.HASH == replay.HASH); DSReplay crep = Replays.FirstOrDefault(s => s.HASH == replay.HASH); if (crep != null) { if (new Version(replay.VERSION) > new Version(crep.VERSION)) { foreach (var ent in crep.DSPlayer.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && replay.PLAYERS.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { replay.PLAYERS.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch { Console.WriteLine("???"); } } DBService.DeleteRep(context, crep.ID); } else { int i = 0; foreach (var ent in replay.PLAYERS.Select(s => new { s.NAME, s.REALPOS })) { try { if (ent.NAME.Length == 64 && crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME.Length < 64) { i++; crep.DSPlayer.Single(x => x.REALPOS == ent.REALPOS).NAME = ent.NAME; } } catch { Console.WriteLine(":("); } } if (i > 0) { context.SaveChanges(); } sReplays.Remove(replay); } } } int j = 0; foreach (dsreplay rep in sReplays) { DSReplay newdbrep = Map.Rep(rep); newdbrep.REPLAYPATH = ""; DBService.SaveReplay(context, newdbrep, true); NewDbReps.Add(newdbrep); j++; if (j % 100 == 0) { context.SaveChanges(); Console.WriteLine($"{j}/{sReplays.Count}"); } } context.SaveChanges(); } return(NewDbReps); }
public static void Replay(DSReplay replay, bool GetDetails) { int maxleaver = 0; int maxkillsum = 0; int minkillsum = -1; int minarmy = -1; int minincome = -1; FixPos(replay); Dictionary <string, double> Breakpoints = new Dictionary <string, double>(DSdata.BreakpointMid); Breakpoints["ALL"] = replay.DURATION * 22.4; foreach (var ent in Breakpoints.Keys.ToArray()) { if (ent == "ALL") { continue; } if (Breakpoints[ent] >= Breakpoints["ALL"]) { Breakpoints.Remove(ent); } } foreach (DSPlayer pl in replay.DSPlayer) { int opppos = DBFunctions.GetOpp(pl.REALPOS); DSPlayer opp = replay.DSPlayer.SingleOrDefault(s => s.REALPOS == opppos); if (opp != null) { pl.OPPRACE = opp.RACE; } if (pl.TEAM == replay.WINNER) { pl.WIN = true; } if (pl.Stats.Any()) { pl.KILLSUM = pl.Stats.OrderBy(o => o.Gameloop).Last().MineralsKilledArmy; } else { pl.KILLSUM = 0; } pl.INCOME = (int)pl.Stats.Sum(s => s.MineralsCollectionRate / 9.15); foreach (DbRefinery r in pl.Refineries.ToArray()) { if (r.Gameloop == 0) { pl.Refineries.Remove(r); } } pl.GAS = (byte)pl.Refineries.Count(); int diff = replay.DURATION - pl.PDURATION; if (diff > maxleaver) { maxleaver = diff; } if (pl.KILLSUM > maxkillsum) { maxkillsum = pl.KILLSUM; } if (minkillsum == -1) { minkillsum = pl.KILLSUM; } else { if (pl.KILLSUM < minkillsum) { minkillsum = pl.KILLSUM; } } if (minarmy == -1) { minarmy = pl.ARMY; } else { if (pl.ARMY < minarmy) { minarmy = pl.ARMY; } } if (minincome == -1) { minincome = pl.INCOME; } else { if (pl.INCOME < minincome) { minincome = pl.INCOME; } } string urace = pl.RACE; if (pl.RACE == "Zagara" || pl.RACE == "Abathur" || pl.RACE == "Kerrigan") { urace = "Zerg"; } else if (pl.RACE == "Alarak" || pl.RACE == "Artanis" || pl.RACE == "Vorazun" || pl.RACE == "Fenix" || pl.RACE == "Karax") { urace = "Protoss"; } else if (pl.RACE == "Raynor" || pl.RACE == "Swann" || pl.RACE == "Nova" || pl.RACE == "Stukov") { urace = "Terran"; } HashSet <string> doubles = new HashSet <string>(); foreach (DbUpgrade upgrade in pl.Upgrades.OrderBy(o => o.Gameloop).ToList()) { if (doubles.Contains(upgrade.Upgrade)) { pl.Upgrades.Remove(upgrade); continue; } doubles.Add(upgrade.Upgrade); UnitModelBase dupgrade = DSdata.Upgrades.FirstOrDefault(s => s.Name == upgrade.Upgrade && s.Race == pl.RACE); if (dupgrade != null) { upgrade.Upgrade = dupgrade.ID.ToString(); } else { UnitModelBase udupgrade = DSdata.Upgrades.FirstOrDefault(s => s.Name == upgrade.Upgrade && s.Race == urace); if (udupgrade != null) { upgrade.Upgrade = udupgrade.ID.ToString(); } else if (upgrade.Upgrade.StartsWith("Tier4WeaponUpgradeLevel")) { UnitModelBase tudupgrade = DSdata.Upgrades.FirstOrDefault(s => s.Name == upgrade.Upgrade && s.Race == ""); if (tudupgrade != null) { upgrade.Upgrade = tudupgrade.ID.ToString(); } } } } pl.Breakpoints = new List <DbBreakpoint>(); foreach (var ent in Breakpoints) { DbBreakpoint bp = GenBreakpoint(pl, (int)ent.Value, ent.Key); bp.Breakpoint = ent.Key; pl.Breakpoints.Add(bp); } } replay.MAXLEAVER = maxleaver; replay.MAXKILLSUM = maxkillsum; replay.MINKILLSUM = minkillsum; replay.MINARMY = minarmy; replay.MININCOME = minincome; FixWinner(replay); replay.HASH = GenHash(replay); using (var md5 = MD5.Create()) { string dirHash = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(Path.GetDirectoryName(replay.REPLAYPATH)))).Replace("-", "").ToLowerInvariant(); string fileHash = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(Path.GetFileName(replay.REPLAYPATH)))).Replace("-", "").ToLowerInvariant(); replay.REPLAY = dirHash + fileHash; } if (GetDetails == false) { foreach (DSPlayer pl in replay.DSPlayer) { pl.Stats.Clear(); pl.Stats = null; pl.Spawns.Clear(); pl.Spawns = null; pl.decUnits.Clear(); pl.decUnits = null; pl.Refineries.Clear(); pl.Refineries = null; pl.Upgrades.Clear(); pl.Upgrades = null; foreach (DbBreakpoint bp in pl.Breakpoints) { bp.Units.Clear(); bp.Units = null; bp.DbUnits.Clear(); bp.DbUnits = null; bp.DbUpgrades.Clear(); bp.DbUpgrades = null; } } } }
public bool AutoUpload() { string hash = "UndEsWarSommer"; string hash2 = "UndEsWarWinter"; using (SHA256 sha256Hash = SHA256.Create()) { string names = String.Join(";", DSdata.Config.Players); hash = GetHash(sha256Hash, names); hash2 = GetHash(sha256Hash, Program.myJson_file); } var client = new RestClient("https://www.pax77.org:9126"); // DEBUG //var client = new RestClient("https://192.168.178.28:9001"); //var client = new RestClient("http://192.168.178.28:9000"); //var client = new RestClient("https://localhost:44315"); //var client = new RestClient("http://localhost:5000"); List <DSReplay> UploadReplays = new List <DSReplay>(); List <dsreplay> UploadReplaysMaped = new List <dsreplay>(); string lastrep = ""; string exp_csv = ""; RestRequest restRequest = null; IRestResponse response = null; if (DSdata.Status.Count > 0) { DSReplay lrep = null; lrep = _db.GetLatestReplay(); if (lrep != null) { lastrep = lrep.GAMETIME.ToString("yyyyMMddHHmmss"); } } DSinfo info = new DSinfo(); info.Name = hash; info.Json = hash2; info.LastRep = lastrep; info.LastUpload = DSdata.Config.LastUpload; info.Total = DSdata.Status.Count; info.Version = DSdata.DesktopVersion.ToString(); _logger.LogInformation("Upload: AutoInfo"); restRequest = new RestRequest("/secure/data/autoinfo", Method.POST); restRequest.RequestFormat = DataFormat.Json; restRequest.AddHeader("Authorization", "DSupload77"); restRequest.AddJsonBody(info); response = client.Execute(restRequest); _logger.LogInformation($"Upload: autoinfo response: {response.Content}"); if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK) { if (response.Content.Contains("UpToDate")) { return(true); } else { lastrep = response.Content; } } else { return(false); } lastrep = new String(lastrep.Where(Char.IsDigit).Take(14).ToArray()); if (!lastrep.Any()) { return(false); } string gametime = lastrep; DateTime gtime = DateTime.MinValue; if (DSdata.Config.FullSend == false && gametime.Length == 14) { int year = int.Parse(gametime.Substring(0, 4)); int month = int.Parse(gametime.Substring(4, 2)); int day = int.Parse(gametime.Substring(6, 2)); int hour = int.Parse(gametime.Substring(8, 2)); int min = int.Parse(gametime.Substring(10, 2)); int sec = int.Parse(gametime.Substring(12, 2)); gtime = new DateTime(year, month, day, hour, min, sec); } UploadReplays = _db.GetUploadReplay(gtime); if (!UploadReplays.Any()) { return(true); } List <string> anonymous = new List <string>(); foreach (DSReplay rep in UploadReplays) { rep.REPLAYPATH = ""; foreach (DSPlayer pl in rep.DSPlayer) { string plname = pl.NAME; if (DSdata.Config.Players.Contains(pl.NAME)) { pl.NAME = "player"; } else { pl.NAME = "player" + pl.REALPOS.ToString(); } } string json = ""; //json = Newtonsoft.Json.JsonConvert.SerializeObject(rep); try { json = System.Text.Json.JsonSerializer.Serialize(rep); } catch (Exception e) { _logger.LogError($"Upload: {e.Message}"); } anonymous.Add(json); } exp_csv = Program.workdir + "\\export.json"; File.WriteAllLines(exp_csv, anonymous); string exp_csv_gz = exp_csv + ".gz"; using (FileStream fileToBeZippedAsStream = new FileInfo(exp_csv).OpenRead()) { using (FileStream gzipTargetAsStream = new FileInfo(exp_csv_gz).Create()) { using (GZipStream gzipStream = new GZipStream(gzipTargetAsStream, CompressionMode.Compress)) { try { fileToBeZippedAsStream.CopyTo(gzipStream); } catch (Exception ex) { _logger.LogError($"Upload: {ex.Message}"); } } } } if (DSdata.Config.FullSend == true) { restRequest = new RestRequest("/secure/data/dbfullsend/" + hash); } else { restRequest = new RestRequest("/secure/data/dbupload/" + hash); } restRequest.RequestFormat = DataFormat.Json; restRequest.Method = Method.POST; restRequest.AddHeader("Authorization", "DSupload77"); restRequest.AddFile("content", exp_csv_gz); response = client.Execute(restRequest); if (response.StatusCode == System.Net.HttpStatusCode.OK) { if (DSdata.Config.FullSend == true) { DSdata.Config.FullSend = false; Status.SaveConfig(); } DSdata.Config.LastUpload = DateTime.UtcNow; Status.SaveConfig(); return(true); } else { return(false); } }