/// <summary> /// reads fron the client's stream and returns a serveruser with the readed data /// </summary> /// <param name="raw_info">The raw data used for recreate the user</param> /// <returns></returns> private MatchUser RecreateUser(string raw_info) { MatchUser queued = null; try { queued = new MatchUser(); ///FORMAT: Username|age|sex|lookingforsex string[] info = raw_info.Split("|"); queued.Username = info[0]; queued.Age = (AGECATEGORY)Enum.Parse(typeof(AGECATEGORY), info[1]); queued.Sex = (GENDER)Enum.Parse(typeof(GENDER), info[2]); queued.LookingForSex = (GENDER)Enum.Parse(typeof(GENDER), info[3]); } catch (Exception e) { Console.WriteLine("MatchController error: RecreateUser error, error message: " + e.Message); queued.Username = ""; } return(queued); }
/// <summary> /// Determines if the curUser is looking for the candidate. If not, it will be added to the cantMatch set /// </summary> /// <param name="curUser"></param> /// <param name="candidate"></param> /// <returns></returns> private bool lookingForThem(MatchUser curUser, MatchUser candidate) { if (curUser.Username == candidate.Username) ///if we spam the start and stop searching button { return(false); } /*MatchUser candidateArch = new MatchUser(); * candidateArch.setArch(candidate);*/ bool success = (candidate.Age == curUser.Age); ///first step success = success && (candidate.Sex == curUser.LookingForSex || curUser.LookingForSex == GENDER.ANY) && DatabaseController.instance().WasntBlockedBy(curUser.Username, candidate.Username); ///we are cool if the candidate is in the gender we are looking for OR if we dont care about it at all success = success && (curUser.Sex == candidate.LookingForSex || candidate.LookingForSex == GENDER.ANY) && DatabaseController.instance().WasntBlockedBy(candidate.Username, curUser.Username); ///and vice versa /*if (success == false) ///then add it to the "unmatchable" group. * { * cantMatch.Add(new MatchUser(curUser), false); * * if (curUser.LookingForSex == GENDER.ANY) ///if it was that flexible, add all gender into the unmatchable group * { * foreach (GENDER sex in Enum.GetValues(typeof(GENDER))) * { * MatchUser archuser = new MatchUser(); * archuser.setArch(sex, curUser.Age); * cantMatch.Add(archuser, false); * } * } * }*/ return(success); }
private UserRoundSlotViewModel CreateVM(Round r, MatchUser matchUser) { return(new UserRoundSlotViewModel() { Round = r, RoundSlotID = r.Sides.SelectMany(s => s.Squads).SelectMany(s => s.Slots).FirstOrDefault(s => s.MatchUserID == matchUser.MatchUserID)?.RoundSlotID }); }
public static MatchUser SetWinner(this MatchUser @this, int reputation) { @this.SetLockUser(); @this.Winner = true; @this.User.Win++; @this.User.Reputation += reputation; return(@this); }
private async Task <bool> CanJoin(MatchUser user) { var max = await _context.MatchSides.Where(s => s.MatchSideID == user.MatchSideID).Select(s => s.MaxUsersCount).FirstOrDefaultAsync(); var count = await _context.MatchUsers.Where(s => s.MatchSideID == user.MatchSideID && s.MatchUserID != user.MatchUserID).CountAsync(); return(count < max); }
public static MatchUser SetDraw(this MatchUser @this, int reputation) { @this.SetLockUser(); @this.Winner = false; @this.User.Draw++; @this.User.Reputation += reputation; return(@this); }
public static MatchUser SetPenalty(this MatchUser @this, int penalty, bool close = false) { @this.User.Reputation -= penalty; if (close) { @this.SetLockUser(); } return(@this); }
private async Task AssignSlot(MatchUser matchUser, RoundSlot roundSlot) { var olderSlots = await _context.RoundSlots.Where(s => s.Squad.Side.RoundID == roundSlot.Squad.Side.RoundID && s.MatchUserID == matchUser.MatchUserID).ToListAsync(); foreach (var olderSlot in olderSlots) { olderSlot.MatchUserID = null; _context.Update(olderSlot); } roundSlot.MatchUserID = matchUser.MatchUserID; _context.Update(roundSlot); await _context.SaveChangesAsync(); }
public static MatchUser SetGoFlagUpdatePassLock(this MatchUser @this, bool go, bool flag, bool update, bool pass = false, bool lockIn = false, bool ready = false) { @this.CanGo = go; @this.CanPass = pass; @this.CanFlag = flag; @this.CanUpdate = update; @this.CanLockIn = lockIn; @this.Ready = ready; return(@this); }
/// <summary> /// 密码匹配 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void simpleButtonCONFIRM_Click(object sender, EventArgs e) { userManage = new UserManage(); if (textBoxLOGIN.Text == "") { labelStatus.Text = "用户名不能为空!"; } else { MatchUser matchUser = userManage.UserLogin(textBoxLOGIN.Text, textBoxPW.Text); if (matchUser == MatchUser.登陆成功) { this.Close(); } else { labelStatus.Text = matchUser.ToString(); } } }
private bool removeFromClientList(string username) { int i = -1; lock (llock) { MatchUser needle = new MatchUser(); do { i++; foreach (MatchUser user in clients) { if (user.Username == username) { needle = user; } } } while (clients.Remove(needle)); } return(i > 0); }
private void handleMatches() { //cantMatch = new Dictionary<MatchUser, bool>(); ///in this, we will store the known "unmatchable" users for (int i = 0; i < clients.Count; i++) { MatchUser curUser = clients[i]; for (int j = i + 1; j < clients.Count; j++) { MatchUser candidate = clients[j]; List <MatchUser> removeables = new List <MatchUser>(); Trace.WriteLine(curUser.Username + " " + candidate.Username); bool success = lookingForThem(curUser, candidate); Trace.WriteLine(success); if (success) { ///create a new instance of privatechat-controller, and match them Console.WriteLine("MatchController: ITS A MATCH! Matched " + curUser.Username + " WITH " + candidate.Username + "!"); Trace.WriteLine("MatchController: ITS A MATCH! Matched " + curUser.Username + " WITH " + candidate.Username + "!"); int port = PortManager.instance().GetPrivateChatPort(); if (port == -1) { Console.WriteLine("MatchController: No available port, no match will happen! Consider restarting the server with a wilder area of ports. Waiting for 1 second then continue"); Trace.WriteLine("MatchController: No available port, no match will happen! Consider restarting the server with a wilder area of ports. Waiting for 1 second then continue"); Thread.Sleep(10000); handleMatches(); return; } string portString = "" + port; byte[] portdata = Encoding.Unicode.GetBytes(portString); Console.WriteLine("MatchController: The following port will be used for match: " + port); NetworkStream curuserStream = curUser.Client.GetStream(); NetworkStream candidatestream = candidate.Client.GetStream(); ///First attempt to reach the client with the portdata try { curuserStream.Write(portdata, 0, portdata.Length); Console.WriteLine("MatchController: Portnum " + port + " sent to the client!"); } catch (Exception e) ///if we lost the first one, reach out the second one, and remove the first { Console.WriteLine("MatchController error: Error during matchmaking: couldnt reach client, error message: " + e.Message); /*clients.RemoveAt(i); * i--;*/ removeables.Add(clients[i]); PortManager.instance().ReturnPrivateChatPort(port); try { byte[] ermsg = Encoding.Unicode.GetBytes("ER"); candidatestream.Write(ermsg, 0, ermsg.Length); } catch (Exception f) ///if we lost that one too, remove it too { Console.WriteLine("MatchController error: Error during matchmaking: couldnt reach candidate, error message: " + f.Message); //clients.RemoveAt(j - 1); removeables.Add(clients[j]); } foreach (MatchUser removeable in removeables) { removeFromClientList(removeable.Username); } break; } Thread.Sleep(200); ///wait a bit to make sure, every package has arrived ///First attempt to reach the candidate with the portdata try { candidatestream.Write(portdata, 0, portdata.Length); Console.WriteLine("Portnum " + port + " sent to the candidate!"); } catch (Exception e) ///if we lost the candidate { Console.WriteLine("MatchController error: Error during matchmaking: couldnt reach candidate, error message: " + e.Message); //clients.RemoveAt(j); removeables.Add(clients[j]); PortManager.instance().ReturnPrivateChatPort(port); try { byte[] ermsg = Encoding.Unicode.GetBytes("ER"); curuserStream.Write(ermsg, 0, ermsg.Length); } catch (Exception f) ///if we lost the original meanwhile { Console.WriteLine("MatchController error: Error during matchmaking: couldnt reach client, error message: " + f.Message); /*clients.RemoveAt(i); * i--; * break;*/ removeables.Add(clients[i]); } foreach (MatchUser removeable in removeables) { removeFromClientList(removeable.Username); } break; } Thread.Sleep(200); ///wait a bit to make sure, every package has arrived ///send the next amount of data: the verifying ///start with the client TimeSpan curtime = DateTime.UtcNow - new DateTime(1970, 1, 1); int secondsSinceEpoch = (int)curtime.TotalSeconds; string conversationid = "OK|" + secondsSinceEpoch + "|" + curUser.Username + "|" + candidate.Username; Console.WriteLine("MatchController: okmessage: " + conversationid); byte[] okmsg = Encoding.Unicode.GetBytes(conversationid); try { //byte[] okmsg = Encoding.Unicode.GetBytes("OK"); curuserStream.Write(okmsg, 0, okmsg.Length); Console.WriteLine("MatchController: Okmsg sent to the client!"); } catch (Exception e) { Console.WriteLine("MatchController error: Error during matchmaking: the client left during that little timestamp, error message: " + e.Message); } Thread.Sleep(200); ///wait a bit to make sure, every package has arrived ///then to the candidate try { //byte[] okmsg = Encoding.Unicode.GetBytes("OK"); candidatestream.Write(okmsg, 0, okmsg.Length); Console.WriteLine("MatchController: Okmsg sent to the candidate!"); } catch (Exception e) { Console.WriteLine("MatchController: Error during matchmaking: the candidate left during that little timestamp, error message " + e.Message); } PrivateChatController pcc = new PrivateChatController(port, CHATTPYE.PRIVATE); Thread privateChatThread = new Thread(pcc.handleConnecting); privateChatThread.IsBackground = true; privateChatThread.Start(); privatechatsThreads.TryAdd(pcc, privateChatThread); lock (llock) { clients.RemoveAt(i); ///ok tbh it kinda looks scray clients.RemoveAt(j - 1); i--; break; } } } } }
public static MatchUser AwardExp(this MatchUser @this, int exp) { LevelSystem.AwardExp(@this.User, exp); return(@this); }
public static bool InRole(this MatchUser @this, MatchRole role) => @this.Role == role;
public MatchUserEvent(Type type, MatchUser user, MatchState state) { this.type = type; this.user = user; this.state = state; }
public MatchUserEvent(Type type, MatchUser user) { this.type = type; this.user = user; }
public async Task <IActionResult> SubscriptionInitial(int id, SubscriptionInitialViewModel vm) { var match = await _context.Matchs.Include(m => m.Sides).FirstOrDefaultAsync(m => m.MatchID == id); if (match == null) { return(NotFound()); } if (match.State != MatchState.Open) { return(RedirectToAction(nameof(Details), new { id })); } if (!vm.AcceptMatchRules) { ModelState.AddModelError("AcceptMatchRules", "Vous devez accepter le réglement de l'opération"); } if (!vm.AcceptSubscription) { ModelState.AddModelError("AcceptSubscription", "Vous devez accepter le traitement des données nécessaires à votre inscription"); } if (!ModelState.IsValid) { vm.Match = match; return(View("SubscriptionInitial", vm)); } using (var transaction = await _context.Database.BeginTransactionAsync()) { var user = await GetUser(); if (user == null) { vm.User.SteamId = UserHelper.GetSteamId(User); vm.User.SteamName = User.Identity.Name; vm.User.UserID = 0; _context.Add(vm.User); await _context.SaveChangesAsync(); user = vm.User; } var matchUser = await _context.MatchUsers.FirstOrDefaultAsync(u => u.MatchID == id && u.UserID == user.UserID); if (matchUser == null) { if (vm.RoundSquadID != null) { // Vérifie que RoundSquadID appartient bien à MatchID vm.RoundSquadID = await _context.RoundSquads.Where(s => s.RoundSquadID == vm.RoundSquadID && s.Side.MatchSide.MatchID == id).Select(s => s.RoundSquadID).FirstOrDefaultAsync(); // Calcule MatchSideID vm.MatchSideID = await _context.RoundSquads.Where(s => s.RoundSquadID == vm.RoundSquadID && s.Side.MatchSide.MatchID == id).Select(s => s.Side.MatchSideID).FirstOrDefaultAsync(); } else if (vm.MatchSideID != null) { // Vérifie que MatchSideID appartient bien à MatchID vm.MatchSideID = await _context.MatchSides.Where(s => s.MatchSideID == vm.MatchSideID && s.MatchID == id).Select(s => s.MatchSideID).FirstOrDefaultAsync(); } else { if (await _context.MatchSides.CountAsync(s => s.MatchID == id) == 1) { vm.MatchSideID = (await _context.MatchSides.FirstAsync(s => s.MatchID == id)).MatchSideID; } } matchUser = new MatchUser() { MatchID = id, UserID = vm.User.UserID, MatchSideID = vm.MatchSideID }; if (matchUser.MatchSideID == null || await CanJoin(matchUser)) { _context.Add(matchUser); await _context.SaveChangesAsync(); } } await transaction.CommitAsync(); } return(RedirectToAction(nameof(Subscription), new { id })); }
public async Task <IActionResult> SubscriptionInitial(int id, SubscriptionInitialViewModel vm) { var match = await _context.Matchs.Include(m => m.Sides).FirstOrDefaultAsync(m => m.MatchID == id); if (match == null) { return(NotFound()); } if (!ModelState.IsValid) { vm.Match = match; return(View("SubscriptionInitial", vm)); } using (var transaction = await _context.Database.BeginTransactionAsync()) { var user = await GetUser(); if (user == null) { vm.User.SteamId = SteamHelper.GetSteamId(User); vm.User.SteamName = User.Identity.Name; vm.User.Name = vm.User.NamePrefix + User.Identity.Name; vm.User.UserID = 0; _context.Add(vm.User); await _context.SaveChangesAsync(); user = vm.User; } var matchUser = await _context.MatchUsers.FirstOrDefaultAsync(u => u.MatchID == id && u.UserID == user.UserID); if (matchUser == null) { if (vm.RoundSquadID != null) { // Vérifie que RoundSquadID appartient bien à MatchID vm.RoundSquadID = await _context.RoundSquads.Where(s => s.RoundSquadID == vm.RoundSquadID && s.Side.MatchSide.MatchID == id).Select(s => s.RoundSquadID).FirstOrDefaultAsync(); // Calcule MatchSideID vm.MatchSideID = await _context.RoundSquads.Where(s => s.RoundSquadID == vm.RoundSquadID && s.Side.MatchSide.MatchID == id).Select(s => s.Side.MatchSideID).FirstOrDefaultAsync(); } else if (vm.MatchSideID != null) { // Vérifie que MatchSideID appartient bien à MatchID vm.MatchSideID = await _context.MatchSides.Where(s => s.MatchSideID == vm.MatchSideID && s.MatchID == id).Select(s => s.MatchSideID).FirstOrDefaultAsync(); } matchUser = new MatchUser() { MatchID = id, UserID = vm.User.UserID, MatchSideID = vm.MatchSideID }; if (matchUser.MatchSideID == null || await CanJoin(matchUser)) { _context.Add(matchUser); await _context.SaveChangesAsync(); } } await transaction.CommitAsync(); } return(RedirectToAction(nameof(Subscription), new { id })); }
public static void SetLockUser(this MatchUser @this) => @this.SetGoFlagUpdatePassLock(false, false, false);
/// <summary> /// Handles the incoming chat requests /// </summary> public void handleRequests() { server = new TcpListener(IPAddress.Any, PortManager.instance().Matchport); clients = new List <MatchUser>(); privatechatsThreads = new ConcurrentDictionary <PrivateChatController, Thread>(); server.Start(); Thread commandThread = new Thread(handleInputCommands); commandThread.Start(); Thread managerThread = new Thread(ThreadManaging); managerThread.Start(); while (true) { TcpClient client = server.AcceptTcpClient(); NetworkStream ns = client.GetStream(); try { KeyValuePair <bool, string> pair = Utility.ReadFromNetworkStream(ns); if (pair.Key == false) { Console.WriteLine("MatchController: invalid syntax on message, discarding request."); continue; } string raw_info = pair.Value; //string raw_info = Utility.ReadFromNetworkStream(ns); //Console.WriteLine("MatchController: Raw info: " + raw_info); if (raw_info[0] == '!') { handleCommands(raw_info); } else { MatchUser joineduser = RecreateUser(raw_info); joineduser.Client = client; if (joineduser.Username == "") { continue; } if (alreadyInQueue(joineduser.Username)) { Console.WriteLine("MatchController: " + joineduser.Username + "is already in the matchqueue, new request is discarded!"); byte[] erdata = Encoding.Unicode.GetBytes("ER|INQUEUE"); ns.Write(erdata, 0, erdata.Length); continue; } Trace.WriteLine("here"); Trace.WriteLine("MatchController: Joined " + joineduser.ToString()); Console.WriteLine("MatchController: Joined " + joineduser.ToString()); byte[] data = Encoding.Unicode.GetBytes("OK"); ns.Write(data, 0, data.Length); Console.WriteLine("MatchController: Replied with " + Encoding.Unicode.GetString(data)); Trace.WriteLine("MatchController: Replied with " + Encoding.Unicode.GetString(data)); lock (llock) { clients.Add(joineduser); } } } catch (Exception e) { Console.WriteLine("Exception in MatchManaging, error message: " + e.Message); } Thread.Sleep(200); handleMatches(); } }
public static void SetFreeze(this MatchUser @this, bool status) => @this.Freeze = status;