public async Task RequireSBAuthentication(string[] contents, SBClient client) { if (client.NSClient == null) { await client.SendAsync("715 " + contents[1], true); } }
private async Task HandleSBCommand(string[] contents, SBClient client) { using Task command = (Task)GetType() .GetMethod($"HandleSB{contents[0].Transform(To.LowerCase, To.SentenceCase)}") .Invoke(this, new object[] { contents, client }); await command; }
public async Task HandleSBAns(string[] contents, SBClient client) { var list = NSClients.Where(x => x.UserHandle == contents[2]).Select(nsc => nsc.SBAuths).FirstOrDefault(); if (list == null || !list.Contains(contents[3])) { await client.SendAsync($"911 {contents[1]}", true); return; } var session = Sessions.Where(x => x.ID.ToString() == contents[4]).FirstOrDefault(); if (session == null) { client.Connection.Client.Close(); return; } var nsc = NSClients.Where(x => x.UserHandle == contents[2]).FirstOrDefault(); nsc.SBAuths.Remove(contents[3]); client.NSClient = nsc; client.AuthString = contents[3]; session.Clients.Add(client); client.Session = session; for (int i = 0; i < session.Clients.Count; i++) { var participant = session.Clients[i]; if (participant == client) { continue; } var partUser = await client.NSClient.Database.Users.FindAsync(participant.NSClient.UserID); await client.SendAsync($"IRO {contents[1]} {i + 1} {session.Clients.Count - 1} {partUser.Email} {partUser.SafeNickname}"); } await client.SendAsync($"ANS {contents[1]} OK"); var usr = await client.NSClient.Database.Users.FindAsync(nsc.UserID); foreach (var cl in session.Clients.Where(x => x != client)) { await cl.SendAsync($"JOI {usr.Email} {usr.SafeNickname}"); } }
public async Task HandleSBUsr(string[] contents, SBClient client) { var list = NSClients.Where(x => x.UserHandle == contents[2]).Select(nsc => nsc.SBAuths).FirstOrDefault(); if (list == null || !list.Contains(contents[3])) { await client.SendAsync($"911 {contents[1]}", true); return; } var nsc = NSClients.Where(x => x.UserHandle == contents[2]).FirstOrDefault(); nsc.SBAuths.Remove(contents[3]); client.NSClient = nsc; client.AuthString = contents[3]; await client.SendAsync($"USR {contents[1]} OK {nsc.UserHandle} {(await nsc.Database.Users.FindAsync(nsc.UserID)).SafeNickname}"); }
public async Task HandleSBMsg(string[] contents, SBClient client) { await RequireSBAuthentication(contents, client); if (client.Session == null) { client.Connection.Client.Close(); return; } var usr = await client.NSClient.Database.Users.FindAsync(client.NSClient.UserID); foreach (var cl in client.Session.Clients.Where(x => x != client)) { await cl.SendAsync($"MSG {usr.Email} {usr.SafeNickname} {contents[3].Substring(0, contents[3].IndexOf("\r\n"))}" + $"\r\n{string.Join("\r\n", string.Join(' ', contents).Split("\r\n").Skip(1))}"); } }
/// <summary> /// Событие при нажатии на кнопку Подключиться /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnConnect_Click(object sender, RoutedEventArgs e) { try { var clnt = new SBClient(this.HostAddress, 25125, this.PlayerName); new MainWindow() { Client = new SBClientModel(clnt) }.Show(); clnt.Start(); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } }
public async Task HandleSBOut(string[] contents, SBClient client) { await RequireSBAuthentication(contents, client); if (client.Session == null) { client.Connection.Client.Close(); return; } client.Session.Clients.Remove(client); foreach (var x in client.Session.Clients) { await x.SendAsync($"BYE {x.NSClient.UserHandle}"); } if (!client.Session.Clients.Any()) { Sessions.RemoveAll(x => x.ID == client.Session.ID); } client.Connection.Client.Close(); }
public event SBClient.TSBCertificateNeededEvent OnCertificateNeeded; public event SBClient.TSBCertificateNeededExEvent OnCertificateNeededEx; public event SBClient.TSBChooseCertificateEvent OnCertificateChoose; #endregion private void OnSecureClientCertificateValidate(Object sender, SBX509.TElX509Certificate certificate, ref bool validate) {
public async Task HandleSBCal(string[] contents, SBClient client) { await RequireSBAuthentication(contents, client); if (!contents[2].IsEmail()) { await client.SendAsync($"208 {contents[1]}", true); return; } var user = await client.NSClient.Database.Users.FindAsync(client.NSClient.UserID); var match = NSClients.Where(x => x.UserHandle == contents[2]).FirstOrDefault(); if (match == null || match.Presence == Presence.Hidden) { await client.SendAsync($"217 {contents[1]}", true); return; } var matchUser = await client.NSClient.Database.Users.FindAsync(match.UserID); Session session = client.Session ?? new Session { ID = (uint)RandomNumberGenerator.GetInt32(10000000), }; if (session.Clients.Contains(client)) { await client.SendAsync($"215 {contents[1]}", true); return; } if ((matchUser.MessagePrivacy && userManager.AreUsersInGroup(ContactList.BlockList, user, matchUser)) || (!matchUser.MessagePrivacy && userManager.AreUsersInGroup(ContactList.AllowList, user, matchUser))) { await client.SendAsync($"216 {contents[1]}", true); return; } session.Clients.Add(client); client.Session = session; Sessions.Add(session); var authString = $"{(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds}.{RandomNumberGenerator.GetInt32(999999)}"; match.SBAuths.Add(authString); // AL and is on block list // OR // BL and it isn't on Allow List. if ((matchUser.MessagePrivacy && userManager.AreUsersInGroup(ContactList.BlockList, user, matchUser)) || (!matchUser.MessagePrivacy && userManager.AreUsersInGroup(ContactList.AllowList, user, matchUser))) { await client.SendAsync($"216 {contents[1]}", true); return; } await match.SendAsync($"RNG {session.ID} {configuration.GetValue<string>("Switchboard")} CKI {authString} {matchUser.Email} {matchUser.SafeNickname}"); await client.SendAsync($"CAL {contents[1]} RINGING 0"); }
/// <summary> /// Конструктор окна с игрой /// </summary> /// <param name="client"></param> public GameWindow(SBClientModel client) { _initLength = 4; _initCount = 0; _initVertical = false; _state = BattleState.Init; _client = client.Client; this.Client = client; InitializeComponent(); myField.Colors = CellValues.BattleFieldColors; myField.BorderColors = BorderValues.BattleFieldBorderColors; enemyField.Colors = CellValues.BattleFieldColors; enemyField.BorderColors = BorderValues.BattleFieldBorderColors; #region мышь указатели enemyField.OnBattleFieldCellMouseEnter += (sender, ea) => { if (_state == BattleState.Turn) { if (ea.Cell.Value == CellValues.None) { ea.Cell.BorderValue = BorderValues.TargetSelection; } } }; enemyField.OnBattleFieldCellMouseLeave += (sender, ea) => { ea.Cell.BorderValue = BorderValues.None; }; enemyField.OnBattleFieldCellMouseUp += (sender, ea) => { if (_state == BattleState.Turn) { if (ea.Cell.Value == CellValues.None) { _state = BattleState.Wait; _cell = ea.Cell; _client.SendFire(ea.Cell.X, ea.Cell.Y); } } }; myField.OnBattleFieldCellMouseEnter += (sender, ea) => { if (_state == BattleState.Init && _initLength > 0) { var ex = _initVertical ? ea.Cell.X : ea.Cell.X + _initLength - 1; var ey = _initVertical ? ea.Cell.Y + _initLength - 1 : ea.Cell.Y; if (ex < 10 && ey < 10) { if (this.IsRectEmpty(myField, ea.Cell.X - 1, ea.Cell.Y - 1, ex + 1, ey + 1)) { for (int x = ea.Cell.X; x <= ex; x++) { for (int y = ea.Cell.Y; y <= ey; y++) { myField[x, y].BorderValue = BorderValues.PlaceSelection; _cells.Add(myField[x, y]); } } } } } }; myField.OnBattleFieldCellMouseLeave += (sender, ea) => { if (_state == BattleState.Init && _cells.Count > 0) { _cells.ForEach(cell => cell.BorderValue = BorderValues.None); _cells.Clear(); } }; myField.OnBattleFieldCellMouseUp += (sender, ea) => { if (ea.Button == MouseButton.Left) { if (_state == BattleState.Init && _initLength > 0) { if (_cells.Count > 0) { _cells.ForEach(cell => { cell.BorderValue = BorderValues.None; cell.Value = CellValues.Own; }); _cells.Clear(); _client.SendPlace(ea.Cell.X, ea.Cell.Y, _initLength, _initVertical); _initCount++; if (_initLength + _initCount == 5) { _initLength--; _initCount = 0; if (_initLength == 0) { _state = BattleState.Wait; } } } } } else if (tt.IsEnabled) { _initVertical = !_initVertical; } }; #endregion _client.OnOpponentFire += (x, y, dead) => { if (_state == BattleState.Wait) { this.Invoke(() => { if (myField[x, y].Value == CellValues.Own) { myField[x, y].Value = CellValues.Dead; if (dead) { SetCompletlyDead(myField, x, y); } } else { myField[x, y].Value = CellValues.FiredEmpty; } }); } }; _client.OnFireResult += (miss, dead) => { if (_state == BattleState.Wait) { if (_cell != null) { this.Invoke(() => { if (miss) { _cell.Value = CellValues.FiredEmpty; SoundPlayer simpleSound = new SoundPlayer(@"C:\Users\Мазимез\Desktop\sbattle\sbattle\SBattle\Voice\Voice_MissClick.wav"); simpleSound.Play(); } else { SoundPlayer simpleSound = new SoundPlayer(@"C:\Users\Мазимез\Desktop\sbattle\sbattle\SBattle\Voice\VoiceSuc.wav"); simpleSound.Play(); _cell.Value = CellValues.Dead; if (dead) { SetCompletlyDead(enemyField, _cell.X, _cell.Y); } } }); _cell = null; } else { MessageBox.Show("Неожиданный результат"); } } }; #region Меню кто одержал победу исправить путь аудио _client.OnGameFinished += winner => { if (_state == BattleState.Wait) { _state = BattleState.Finished; this.Invoke(() => { SoundPlayer simpleSound = new SoundPlayer(@"C:\Users\Мазимез\Desktop\sbattle\sbattle\SBattle\Voice\VoiceWin.wav"); simpleSound.Play(); MessageBox.Show(this, winner + " одержал победу!"); //создание объекта // MediaPlayer player = new MediaPlayer(); //загрузка звука из ресурсов //загрузка выбранного файла // player.Open(new Uri(@"pack://*****:*****@"pack://application:,,,/pic/orig.jpg", // player.Play(); //SoundPlayer simpleSound = new SoundPlayer(@"C:\Users\Мазимез\Desktop\sbattle\sbattle\SBattle\Voice\VoiceWin.wav"); // simpleSound.Play(); this.DialogResult = true; this.Close(); }); } }; #endregion _client.OnTurn += () => { if (_state == BattleState.Wait) { _state = BattleState.Turn; } }; BattleState st = BattleState.Finished; #region Шляпа если сервер потерпит крах _client.OnConnectionLost += () => { if (_state != BattleState.Finished) { this.Invoke(() => chat.AppendLine("Переподключение...")); st = _state; _state = BattleState.Wait; if (!_client.Reconnect()) { this.Invoke(() => chat.AppendLine("Ошибка")); } else { this.Invoke(() => chat.AppendLine("Соединение установлено. Восстанавливается сеанс...")); } } }; _client.OnConnectedSuccessful += () => { if (_state != BattleState.Finished) { //this.Invoke(() => chat.AppendLine("Сессия восстановлена.")); _state = st; } }; _client.OnSessionRestoreFailed += () => { if (_state != BattleState.Finished) { this.Invoke(() => { MessageBox.Show(this, "Ошибка восстановления сессии."); this.DialogResult = false; this.Close(); }); } }; }
/// <summary> /// Конструктор окна с игрой /// </summary> /// <param name="client"></param> public GameWindow(SBClientModel client) { _initLength = 4; _initCount = 0; _initVertical = false; _state = BattleState.Init; _client = client.Client; this.Client = client; InitializeComponent(); myField.Colors = CellValues.BattleFieldColors; myField.BorderColors = BorderValues.BattleFieldBorderColors; enemyField.Colors = CellValues.BattleFieldColors; enemyField.BorderColors = BorderValues.BattleFieldBorderColors; #region мышь указатели enemyField.OnBattleFieldCellMouseEnter += (sender, ea) => { if (_state == BattleState.Turn) { if (ea.Cell.Value == CellValues.None) { ea.Cell.BorderValue = BorderValues.TargetSelection; } } }; enemyField.OnBattleFieldCellMouseLeave += (sender, ea) => { ea.Cell.BorderValue = BorderValues.None; }; enemyField.OnBattleFieldCellMouseUp += (sender, ea) => { if (_state == BattleState.Turn) { if (ea.Cell.Value == CellValues.None) { _state = BattleState.Wait; _cell = ea.Cell; _client.SendFire(ea.Cell.X, ea.Cell.Y); } } }; myField.OnBattleFieldCellMouseEnter += (sender, ea) => { if (_state == BattleState.Init && _initLength > 0) { var ex = _initVertical ? ea.Cell.X : ea.Cell.X + _initLength - 1; var ey = _initVertical ? ea.Cell.Y + _initLength - 1 : ea.Cell.Y; if (ex < 10 && ey < 10) { if (this.IsRectEmpty(myField, ea.Cell.X - 1, ea.Cell.Y - 1, ex + 1, ey + 1)) { for (int x = ea.Cell.X; x <= ex; x++) { for (int y = ea.Cell.Y; y <= ey; y++) { myField[x, y].BorderValue = BorderValues.PlaceSelection; _cells.Add(myField[x, y]); } } } } } }; myField.OnBattleFieldCellMouseLeave += (sender, ea) => { if (_state == BattleState.Init && _cells.Count > 0) { _cells.ForEach(cell => cell.BorderValue = BorderValues.None); _cells.Clear(); } }; myField.OnBattleFieldCellMouseUp += (sender, ea) => { if (ea.Button == MouseButton.Left) { if (_state == BattleState.Init && _initLength > 0) { if (_cells.Count > 0) { _cells.ForEach(cell => { cell.BorderValue = BorderValues.None; cell.Value = CellValues.Own; }); _cells.Clear(); _client.SendPlace(ea.Cell.X, ea.Cell.Y, _initLength, _initVertical); _initCount++; if (_initLength + _initCount == 5) { _initLength--; _initCount = 0; if (_initLength == 0) { _state = BattleState.Wait; } } } } } else if (tt.IsEnabled) { _initVertical = !_initVertical; } }; #endregion _client.OnOpponentFire += (x, y, dead) => { if (_state == BattleState.Wait) { this.Invoke(() => { if (myField[x, y].Value == CellValues.Own) { myField[x, y].Value = CellValues.Dead; if (dead) { SetCompletlyDead(myField, x, y); } } else { myField[x, y].Value = CellValues.FiredEmpty; } }); } }; _client.OnFireResult += (miss, dead) => { if (_state == BattleState.Wait) { if (_cell != null) { this.Invoke(() => { if (miss) { _cell.Value = CellValues.FiredEmpty; } else { _cell.Value = CellValues.Dead; if (dead) { SetCompletlyDead(enemyField, _cell.X, _cell.Y); } } }); _cell = null; } else { MessageBox.Show("Неожиданный результат"); } } }; _client.OnGameFinished += winner => { if (_state == BattleState.Wait) { _state = BattleState.Finished; this.Invoke(() => { MessageBox.Show(this, winner + " одержал победу!"); this.DialogResult = true; this.Close(); }); } }; _client.OnTurn += () => { if (_state == BattleState.Wait) { _state = BattleState.Turn; } }; BattleState st = BattleState.Finished; _client.OnConnectionLost += () => { if (_state != BattleState.Finished) { this.Invoke(() => chat.AppendLine("Переподключение...")); st = _state; _state = BattleState.Wait; if (!_client.Reconnect()) { this.Invoke(() => chat.AppendLine("Ошибка")); } else { this.Invoke(() => chat.AppendLine("Соединение установлено. Восстанавливается сеанс...")); } } }; _client.OnConnectedSuccessful += () => { if (_state != BattleState.Finished) { //this.Invoke(() => chat.AppendLine("Сессия восстановлена.")); _state = st; } }; _client.OnSessionRestoreFailed += () => { if (_state != BattleState.Finished) { this.Invoke(() => { MessageBox.Show(this, "Ошибка восстановления сессии."); this.DialogResult = false; this.Close(); }); } }; }