/// <summary>
 /// Добавляет обновление в БД и скачивает файл на сервер.
 /// </summary>
 /// <param name="uploadUpdate">Объект файла с веб формы</param>
 /// <param name="description">Описание обновления</param>
 /// <param name="version">Версия обновления</param>
 public void AddUpdate(IFormFile uploadUpdate, string description, int version)
 {
     // Если переданный файл не null.
     if (uploadUpdate != null)
     {
         // Имя файла с рандомной частью.
         string path = $"/{AppConfiguration["UpdatesCatalog"]}/{Path.GetRandomFileName() + uploadUpdate.FileName}";
         // Сохранить файл в папку.
         using (var fileStream = new FileStream(AppEnvironment.WebRootPath + path, FileMode.Create))
         {
             uploadUpdate.CopyTo(fileStream);
         }
         // Создать объект обновления.
         var updateFile = new ClientUpdate
         {
             Date     = DateTime.Now.Date,
             Filename = path,
             Version  = version,
             Info     = description
         };
         // Добавить в бд и сохранить.
         Database.Updates.Create(updateFile);
         Database.Save();
     }
 }
Example #2
0
        public async Task <ActionResult <Client> > Put(Guid id, [FromBody] ClientUpdate entity)
        {
            try
            {
                var client = _mapper.Map <Client>(entity);
                if (client != null)
                {
                    var existingClient = await _clientService.GetByIdAsync(client.Id);

                    client.CreatedAt = existingClient.CreatedAt;
                    client.UpdatedAt = DateTime.UtcNow;
                    client.Status    = existingClient.Status;
                }

                var itemCount = await _clientService.UpdateAsync(id, client);

                if (itemCount > 0)
                {
                    return(CreatedAtAction(nameof(Get), new { id = client.Id }, client));
                }
                return(NotFound());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #3
0
        private ClientUpdate GenClientUpdate(double dt)
        {
            ClientUpdate.PressedKeys pressed = ClientUpdate.PressedKeys.None;
            //Polls input
            if (input.IsKeyPressed(OpenTK.Input.Key.W))
            {
                pressed |= ClientUpdate.PressedKeys.W;
            }
            if (input.IsKeyPressed(OpenTK.Input.Key.A))
            {
                pressed |= ClientUpdate.PressedKeys.A;
            }
            if (input.IsKeyPressed(OpenTK.Input.Key.S))
            {
                pressed |= ClientUpdate.PressedKeys.S;
            }
            if (input.IsKeyPressed(OpenTK.Input.Key.D))
            {
                pressed |= ClientUpdate.PressedKeys.D;
            }
            var left  = input.IsMousePressed(OpenTK.Input.MouseButton.Left);
            var right = input.IsMousePressed(OpenTK.Input.MouseButton.Right);
            var cU    = new ClientUpdate(sManager.LastSentClientUpdateID + 1, playerID, pressed, input.CalcMouseAngle(), left, right, dt);

            return(cU);
        }
Example #4
0
        /// <summary>
        /// Sends updated client state/inputs to the server and also returns it.
        /// </summary>
        private ClientUpdate SendClientupdate(double dt)
        {
            ClientUpdate cU = GenClientUpdate(dt);

            sManager.SendClientUpdateAsync(cU).Detach();
            return(cU);
        }
Example #5
0
        public async Task <ICommandOutput> Handler(ClientUpdate command)
        {
            command.Validate();
            if (command.Invalid)
            {
                return(new GenericCommandResult(false, "Dados Inválidos", command.Notifications));
            }

            var name     = new Name(command.FirstName, command.LastName);
            var document = new Document(command.NuberDocument);

            if (name.Invalid)
            {
                new GenericCommandResult(false, "Dados do name inválidos", name.Notifications);
            }

            if (document.Invalid)
            {
                new GenericCommandResult(false, "Dados do documento inválidos", document.Notifications);
            }

            var client = await _repositoryClient.GetById(command.Id);

            client.Update(command.FirstName, command.LastName, command.NuberDocument, command.Telephone, command.Address);
            await _repositoryClient.Update(client);

            return(new GenericCommandResult(true, "Dados do cliente atualizados com sucesso", client));
        }
Example #6
0
 private ClientUpgrade( string domainID )
 {
     WebState ws = new WebState(domainID, domainID);
        hostAddress = DomainProvider.ResolveLocation( domainID ).ToString();
        service = new ClientUpdate();
        service.Url = hostAddress + "/ClientUpdate.asmx";
        ws.InitializeWebClient(service, domainID);
 }
Example #7
0
        // GET: Client/Edit/
        public async Task <ActionResult> Edit(Guid id)
        {
            var client = await _repositoryClient.GetById(id);

            ViewBag.success = false;

            var _clientUpdate = new ClientUpdate(client.Id, client.Name.FirstName, client.Name.LastName, client.CPF.Number, client.Telephone, client.Address);

            return(PartialView(_clientUpdate));
        }
 public async Task OnUpdate(ClientUpdate e)
 {
     try
     {
         await _connection.Proxy.OnUpdate(e);
     }
     catch
     {
         Debugger.Break();
     }
 }
Example #9
0
        /// <summary>
        /// Processes clientUpdate and adds it to the queue.
        /// </summary>
        /// <param name="msg">ClientUpdate</param>
        /// <returns>Task that completes when the ClienUpdate has been enqueued.</returns>
        async Task HandleClientUpdateAsync(byte[] msg)
        {
            var clientUpdate = await Task.Run(() => ClientUpdate.Decode(msg));

            var tmp = clientUpdates;

            while (tmp != Interlocked.CompareExchange(ref clientUpdates, tmp.Add(clientUpdate), tmp))
            {
                tmp = clientUpdates;
            }
        }
Example #10
0
    } // referralAgencies

    public Client AddNewClient(ClientUpdate newClient) {
      if (!Guid.Empty.Equals(newClient.Id))
        throw new Exception("Client has an id - does it already exist?");

      newClient.Id = Guid.NewGuid();
      newClient.Address.Id = Guid.NewGuid();
      newClient.Demographics.Id = Guid.NewGuid();
      clients.Add(newClient.clientData());
      Commit();

      return Client(newClient.Id);      
    } // AddNewClient
Example #11
0
        /// <summary>
        /// Initializes a new instance of the object.
        /// </summary>
        /// <param name="domainID">Identifier of the domain that the user belongs to.</param>
        private ClientUpgrade(string domainID)
        {
            // Set the web state when authentication is really required...
            WebState ws = new WebState(domainID, domainID);

            // Get the address of the host service.
            hostAddress = DomainProvider.ResolveLocation(domainID).ToString();
            // Setup the url to the server.
            service     = new ClientUpdate();
            service.Url = hostAddress + "/ClientUpdate.asmx";
            ws.InitializeWebClient(service, domainID);
        }
        public IHttpActionResult PutClient(Guid id, ClientUpdate client)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            if (id != client.Id)
                return BadRequest();

            repo_.Update(client);
            repo_.AddClientNote(id, NewNote.Log("Updated details"));

            return GetClient(id);
        } // PutClient
Example #13
0
        public async Task <IActionResult> Update([FromBody] ClientUpdate model)
        {
            try
            {
                var result = await _clientService.Update(model);

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        private Tuple <Client, RiskMap> createClientWithRiskMap()
        {
            var clientId = createClient(project()).Id;
            var risks    = riskMap(riskMapId());

            var update = new ClientUpdate()
            {
                Id = clientId,
            };

            updateClient(update);

            return(Tuple.Create(getClient(clientId), risks));
        } // createClientWithRiskMap
Example #15
0
        public async Task <ActionResult> Edit(ClientUpdate command)
        {
            command.Telephone     = String.Join("", System.Text.RegularExpressions.Regex.Split(command.Telephone, @"[^\d]"));
            command.NuberDocument = String.Join("", System.Text.RegularExpressions.Regex.Split(command.NuberDocument, @"[^\d]"));

            var _client = (GenericCommandResult)await _clientHandler.Handler(command);

            if (_client.Success)
            {
                ViewBag.success = true;
            }

            return(PartialView());
        }
        public async Task <IActionResult> UpdateClientProfile(int id, ClientUpdate clientUpdate)
        {
            if (CurrentUserId != id)
            {
                return(BadRequest((sentId: id, currentUserId: CurrentUserId)));
            }

            var result = await _clientManager.UpdateClientProfile(id, clientUpdate);

            if (result.Succeeded)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
Example #17
0
        public async Task <IActionResult> Update(ClientUpdate model)
        {
            if (model.MobileNumber.StartsWith('0'))
            {
                model.MobileNumber = "962" + model.MobileNumber.Substring(1);
            }
            else
            {
                model.MobileNumber = "962" + model.MobileNumber;
            }


            Client client = await _db.Clients.Where(x => x.Id == model.Id).FirstOrDefaultAsync();

            long userId = _principalService.GetUserId();

            if (!string.IsNullOrEmpty(model.ClientFullName))
            {
                client.ClientFullName = model.ClientFullName;
            }

            if (!string.IsNullOrEmpty(model.MobileNumber))
            {
                client.MobileNumber = model.MobileNumber;
            }

            if (!string.IsNullOrEmpty(model.Address))
            {
                client.Address = model.Address;
            }
            if (!string.IsNullOrEmpty(model.Email))
            {
                client.Email = model.Email;
            }
            client.UpdatedAt = DateTime.Now;
            client.UpdatedBy = userId;
            var result = await _db.SaveChangesAsync();

            await UpdateUser((long)client.UserId, model.Username, model.Email, model.Password);

            if (result == 1)
            {
                return(new OkObjectResult("تم تحديث البيانات بنجاح"));
            }


            throw new Exception("حصل خطأ");
        }
        /// <summary>
        /// Получить последнее обновление.
        /// </summary>
        /// <returns>Dto последнего загруженного обновления</returns>
        public ClientUpdateDTO GetLastUpdate()
        {
            // Найти данные последнего обновления в бд.
            ClientUpdate update = Database.Updates.GetAll().LastOrDefault();

            // Если обновление не найдено.
            if (update is null)
            {
                throw new ValidationException("Обновления отсутствуют.", "");
            }
            // Создать ссылку скачивания.
            var downloadUrl = new Uri($"http://{Environment.MachineName}:{AppConfiguration["ServerPort"]}{update.Filename}");

            // Вернуть обновление для передачи клиенту.
            return(new ClientUpdateDTO(update.Date, update.Version, update.Info, update.Filename, downloadUrl));
        }
        public void update_client()
        {
            Guid clientId = createClient(project()).Id;

            var update = new ClientUpdate()
            {
                Id   = clientId,
                Name = "TEST__Fred"
            };

            updateClient(update);

            var client = getClient(clientId);

            Assert.AreEqual("TEST__Fred", client.Name);
        } // FindAndUpdate
        /// <summary>
        /// Проверяет начилие обновления для клиента.
        /// </summary>
        /// <param name="version">Текущая версия клиента</param>
        /// <returns>DTO объект обновления</returns>
        public ClientUpdateDTO CheckUpdate(int version)
        {
            // Найти данные последнего обновления в бд.
            ClientUpdate update = Database.Updates.Find(v => v.Version > version).OrderByDescending(x => x.Id).FirstOrDefault();

            // Если обновление не найдено.
            if (update is null)
            {
                throw new ValidationException("Установлена последняя версия программы.", "");
            }
            // Создать ссылку скачивания.
            var downloadUrl = new Uri($"http://{Environment.MachineName}:{AppConfiguration["ServerPort"]}{update.Filename}");

            // Вернуть обновление для передачи клиенту.
            return(new ClientUpdateDTO(update.Date, update.Version, update.Info, update.Filename, downloadUrl));
        }
Example #21
0
    } // AddNewClient

    public Client Update(ClientUpdate clientUpdate) {
      var existingClient = clients.
        Where(c => c.Id == clientUpdate.Id).
        Include(c => c.Address).
        Include(c => c.Demographics).
        Single();

      if (existingClient == null)
        throw new Exception("Client not found - can't update");

      existingClient.CopyFrom(clientUpdate.clientData());

      Commit(existingClient);

      return Client(clientUpdate.Id);
    } // Update
 public void ApplyClientUpdate(ClientUpdate data, uint index)
 {
     if (index == playerIndex)
     {
         transform.position = data.position;
         transform.rotation = Quaternion.Euler(data.euler);
     }
     else if (remoteClients.ContainsKey(index))
     {
         remoteClients[index].ApplyClientUpdate(data, index);
     }
     else
     {
         Debug.LogError("Received ClientUpdate for a remoteClient that we haven't spawned");
     }
 }
Example #23
0
        private void SendCommandsToServer(GameActCommands commands)
        {
            var clientUpdate = new ClientUpdate(commands);

            Network.SendPacket(clientUpdate, serverConnection);

            /*
             * try
             * {
             *  Network.SendPacket(clientUpdate, server.GetStream());
             * }
             * catch (Exception e)
             * {
             *  disconnectedActs++;
             * }
             */
        }
        public IActionResult UploadUpdate()
        {
            // Сформировать список обновлений клиента.
            IEnumerable <ClientUpdate> updates = ClientUpdate.GetAllUpdates();
            var uploadVm = updates is null
                ? new UploadUpdateVm()
            {
                AllUpdates = new List <ClientUpdate>(), Version = 1000
            }
                : new UploadUpdateVm()
            {
                AllUpdates = updates, Version = updates.LastOrDefault().Version + 1
            };

            // Вернуть представление.
            return(View(uploadVm));
        }
Example #25
0
        public ActionResult Inscription([Bind(Include = "Nom,Prenom,Login,MotDePasse,RetapezMotDePasse,Email,Ville,Tel")] ClientUpdate c)
        {
            if (ModelState.IsValid)
            {
                Client newClient = new Client(c.Login, c.MotDePasse, c.Nom, c.Prenom, c.Email, c.Ville, c.Tel);

                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:60076");
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var message = client.GetAsync("api/Auth/Inscription?Login="******"&MotDePasse=" + newClient.MotDePasse + "&Nom=" + newClient.Nom + "&Prenom=" + newClient.Prenom + "&Email=" + newClient.Email + "&Ville=" + newClient.Ville + "&Tel=" + newClient.Tel).Result;

                if (message.StatusCode == HttpStatusCode.Created)
                {
                    ViewData["bienAjouter"] = "success";
                    return(View("Inscription"));
                }
                else
                {
                    ViewData["erreurAuth"] = "erreurInscription";
                    return(View("Inscription", c));
                }
            }
            return(View("Inscription", c));
        }
Example #26
0
        public async Task <GeneralResponse> UpdateClientProfile(int id, ClientUpdate clientUpdate)
        {
            var response = new GeneralResponse();
            var user     = await _userManager.FindByIdAsync(id.ToString());

            var client = GetById <Client>(id);

            client = _mapper.Map(clientUpdate, client);
            client.User.ModifiedDate = DateTime.UtcNow;
            client.User.ModifiedBy   = client.User.FirstName;
            var existingUser = await _userManager.FindByEmailAsync(client.User.Email);

            if (existingUser != null && user != existingUser)
            {
                response.Succeeded = false;
                return(response.ErrorHandling <ClientManager>("Email is already in use", objects: (existingUser, clientUpdate)));
            }

            Update(client, client.User.FirstName);
            await _userManager.UpdateAsync(user);

            response.Succeeded = true;
            return(response);
        }
        public async Task <IActionResult> UploadUpdate(UploadUpdateVm updateVm)
        {
            try
            {
                // Загрузить обновление.
                ClientUpdate.AddUpdate(updateVm.UpdateFile, updateVm.Description, updateVm.Version);
                // Поулчить последнее загруженное обновление.
                ClientUpdateDTO update = ClientUpdate.GetLastUpdate();
                // Отправить всем клиентам вызов проверки обновления.
                await WorkHub.Clients.All.SendAsync("CheckUpdate");

                return(RedirectToAction("UploadUpdate"));
            }
            catch (DbUpdateException dbEx)
            {
                // При ошибке записать в лог и вывести страницу ошибок.
                string error = dbEx.InnerException is null ? dbEx.Message : dbEx.InnerException.Message;
                Logger.LogError($"Ошибка загрузки обновления - {error}");
                return(View("Error", new ErrorVm()
                {
                    ErrorMessage = error
                }));
            }
        }
Example #28
0
 public ClientStatusUpdate(ClientUpdate updateType)
 {
     this.Update = updateType;
 }
        public MainWindowModel()
        {
            // 注册日志
            var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");

            XmlConfigurator.ConfigureAndWatch(logCfg);
            _logger = LogManager.GetLogger("ClientLog");

            ZipHelper.ExtractProgress += ZipHelper_ExtractProgress;

            try
            {
                Task.Run(() =>
                {
                    // 次数
                    int time = 0;
                    bool run = true;
                    do
                    {
                        KillMainProcess("Client");
                        Thread.Sleep(1000);

                        Process[] runApplications = Process.GetProcessesByName("Client");
                        if (runApplications.Length == 0)
                        {
                            run = false;
                        }

                        time += 1;
                        if (time == 5)
                        {
                            // 尝试5次以后就不继续尝试了。
                            run = false;
                        }
                    }while (run);

                    // 获取原始路径
                    if (File.Exists("source.info"))
                    {
                        try
                        {
                            _sourcePath = "source.info".FileDeSerialize() as string;
                            _logger.Info($"反序列化原始路径:{_sourcePath}");
                        }
                        catch (Exception ex)
                        {
                            _logger.Warn(ex.Message);
                            MessageBox.Show($"序列化失败:{ex.Message}");
                            return;
                        }

                        // 清除原始文件
                        var hasPath = Directory.Exists(_sourcePath);
                        if (hasPath)
                        {
                            _logger.Info($"清除原始文件");

                            var allFiles = Directory.GetFiles(_sourcePath);
                            var files    = allFiles?.Where(f => f.LastIndexOf("user.info") == -1);
                            if (files != null)
                            {
                                foreach (var f in files)
                                {
                                    File.Delete(f);
                                    _logger.Info($"正在删除文件:{f}");
                                }
                            }
                        }
                    }
                    else
                    {
                        _logger.Info("没有找到source.info");
                        MessageBox.Show("升级失败!由于网络等因素,关闭后从新升级!");
                        System.Environment.Exit(-5);
                        return;
                    }

                    _logger.Info($"获取服务端客户端配置文件");

                    // 获取服务端客户端配置文件
                    if (File.Exists(CommonPath.ServiceUpdate.CombineCurrentDirectory()))
                    {
                        _serviceInfo = CommonPath.ServiceUpdate.CombineCurrentDirectory().LoadFromXml <ServiceUpdate>();
                    }
                    // 获取本地客户端配置文件
                    if (File.Exists(CommonPath.ClientUpdate.CombineCurrentDirectory()))
                    {
                        _clientInfo = (CommonPath.ClientUpdate.CombineCurrentDirectory().LoadFromXml <ClientUpdate>());
                    }

                    _logger.Info($"解压文件到原始路径");

                    var erroMessage = string.Empty;
                    // 解压文件到原始路径
                    var success = ZipHelper.Decompress(_sourcePath, Path.Combine(Environment.CurrentDirectory, _serviceInfo.Path), out erroMessage);
                    if (!success)
                    {
                        _logger.Warn(erroMessage);
                        MessageBox.Show($"序列化失败:{erroMessage}");
                        System.Environment.Exit(-5);
                        return;
                    }

                    _logger.Info($"1.正在解压文件{_sourcePath} To {Path.Combine(Environment.CurrentDirectory, _serviceInfo.Path)}");

                    // 删除原始路径的ZIP文件
                    System.IO.File.Delete(Path.Combine(_sourcePath, _serviceInfo.Path));
                    _logger.Info($"删除下载的Zip文件;{Path.Combine(_sourcePath, _serviceInfo.Path)}");

                    _clientInfo.UpdateTime  = DateTime.Now;
                    _clientInfo.Version     = _serviceInfo.Version;
                    _clientInfo.VersionType = _serviceInfo.VersionType;
                    _clientInfo.Conent      = _serviceInfo.Conent;

                    try
                    {
                        // 更新客户端文件
                        Path.Combine(_sourcePath, "ClientUpdate.xml").SaveToXml <ClientUpdate>(_clientInfo);

                        // 设置更新路径
                        Path.Combine(_sourcePath, "target.info").FileSerialize(Environment.CurrentDirectory);
                    }
                    catch (Exception ex)
                    {
                        _logger.Info($"{ex.Message}");
                        MessageBox.Show("升级失败!由于网络等因素,关闭后从新升级!");
                        System.Environment.Exit(-5);
                    }

                    _logger.Info($"启动任务;{Path.Combine(_sourcePath, "Client.exe")}");

                    // 启动原始程序 Client
                    try
                    {
                        Process process                    = new Process();
                        process.StartInfo.FileName         = Path.Combine(_sourcePath, "Client.exe");
                        process.StartInfo.WorkingDirectory = _sourcePath;
                        process.Start();
                    }
                    catch (Exception ex)
                    {
                        _logger.Info($"启动任务失败:{ex.Message}");
                        MessageBox.Show("升级失败!由于网络等因素,关闭后从新升级!");
                        System.Environment.Exit(-5);
                    }

                    _logger.Info($"已经启动;{Path.Combine(_sourcePath, "Client.exe")}");

                    // 关闭当前程序
                    GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        System.Environment.Exit(-5);
                        _logger.Info($"关闭当前升级程序,升级成功.");
                    });
                });
            }
            catch (Exception ex)
            {
                _logger.Info(ex.Message);

                MessageBox.Show("升级失败!由于网络等因素,关闭后从新升级!");
                System.Environment.Exit(-5);
            }
        }
Example #30
0
        /// <summary>
        /// Packets handled in this function are 'internal' and cannot be overriden.
        /// </summary>
        internal bool HandlePacket(PacketEventArgs e)
        {
            if (IsCaptcha)
            {
                switch ((AresId)e.Packet.Id)
                {
                case AresId.MSG_CHAT_CLIENT_FASTPING:
                    FastPing = true;
                    return(true);

                case AresId.MSG_CHAT_CLIENT_DUMMY:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_AUTOLOGIN:
                    AutoLogin login = (AutoLogin)e.Packet;
                    AresCommands.HandleAutoLogin(server, this, login.Sha1Password);
                    return(true);

                case AresId.MSG_CHAT_CLIENT_PUBLIC:
                    ClientPublic pub = (ClientPublic)e.Packet;
                    FinishCaptcha(pub.Message);
                    return(true);

                case AresId.MSG_CHAT_CLIENT_EMOTE:
                    ClientEmote emote = (ClientEmote)e.Packet;
                    FinishCaptcha(emote.Message);
                    return(true);

                case AresId.MSG_CHAT_CLIENT_ADDSHARE:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_UPDATE_STATUS:
                    ClientUpdate update = (ClientUpdate)e.Packet;

                    LastUpdate = DateTime.Now;
                    NodeIp     = update.NodeIp;
                    NodePort   = update.NodePort;
                    return(true);

                default:
                    break;
                }
                return(false);
            }
            else if (LoggedIn)
            {
                switch ((AresId)e.Packet.Id)
                {
                case AresId.MSG_CHAT_CLIENT_FASTPING:
                    FastPing = true;
                    return(true);

                case AresId.MSG_CHAT_CLIENT_DUMMY:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_PUBLIC:
                    ClientPublic pub = (ClientPublic)e.Packet;

                    if (AresCommands.HandlePreCommand(server, this, pub.Message))
                    {
                        return(true);
                    }

                    if (Muzzled)
                    {
                        server.SendAnnounce(this, Strings.AreMuzzled);
                        return(true);
                    }
                    break;

                case AresId.MSG_CHAT_CLIENT_EMOTE:
                    ClientEmote emote = (ClientEmote)e.Packet;

                    if (AresCommands.HandlePreCommand(server, this, emote.Message))
                    {
                        return(true);
                    }

                    if (Muzzled)
                    {
                        server.SendAnnounce(this, Strings.AreMuzzled);
                        return(true);
                    }
                    break;

                case AresId.MSG_CHAT_CLIENT_COMMAND:
                    Command cmd = (Command)e.Packet;
                    if (AresCommands.HandleCommand(server, this, cmd.Message))
                    {
                        return(true);
                    }
                    break;

                case AresId.MSG_CHAT_CLIENT_PVT:
                    Private pvt = (Private)e.Packet;

                    if (Muzzled && !server.Config.MuzzledPMs)
                    {
                        pvt.Message = "[" + Strings.AreMuzzled + "]";
                        SendPacket(pvt);

                        return(true);
                    }

                    break;

                case AresId.MSG_CHAT_CLIENT_AUTHREGISTER: {
                    AuthRegister reg = (AuthRegister)e.Packet;
                    AresCommands.HandleRegister(server, this, reg.Password);
                    return(true);
                }

                case AresId.MSG_CHAT_CLIENT_AUTHLOGIN: {
                    AuthLogin login = (AuthLogin)e.Packet;
                    AresCommands.HandleLogin(server, this, login.Password);
                    return(true);
                }

                case AresId.MSG_CHAT_CLIENT_AUTOLOGIN: {
                    AutoLogin login = (AutoLogin)e.Packet;
                    AresCommands.HandleAutoLogin(server, this, login.Sha1Password);
                    return(true);
                }

                case AresId.MSG_CHAT_CLIENT_ADDSHARE:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_IGNORELIST:
                    Ignored ignore = (Ignored)e.Packet;
                    if (ignore.Ignore)
                    {
                        lock (Ignored) {
                            if (!Ignored.Contains(ignore.Username))
                            {
                                Ignored.Add(ignore.Username);
                                server.SendAnnounce(this, String.Format(Strings.Ignored, ignore.Username));
                            }
                        }
                    }
                    else
                    {
                        lock (Ignored) {
                            if (Ignored.Contains(ignore.Username))
                            {
                                Ignored.Remove(ignore.Username);
                                server.SendAnnounce(this, String.Format(Strings.Unignored, ignore.Username));
                            }
                        }
                    }
                    return(true);

                case AresId.MSG_CHAT_CLIENT_UPDATE_STATUS:
                    ClientUpdate update = (ClientUpdate)e.Packet;

                    LastUpdate = DateTime.Now;
                    NodeIp     = update.NodeIp;
                    NodePort   = update.NodePort;
                    server.SendPacket((s) =>
                                      s.Vroom == Vroom &&
                                      s.CanSee(this),
                                      new ServerUpdate(this));

                    return(true);

                case AresId.MSG_CHAT_CLIENT_DIRCHATPUSH:
                    ClientDirectPush push = (ClientDirectPush)e.Packet;

                    if (Encoding.UTF8.GetByteCount(push.Username) < 2)
                    {
                        SendPacket(new DirectPushError(4));
                        return(true);
                    }

                    if (push.TextSync.Length < 16)
                    {
                        SendPacket(new DirectPushError(3));
                        return(true);
                    }

                    IClient target = server.FindUser(s => s.Name == push.Username);

                    if (target == null)
                    {
                        SendPacket(new DirectPushError(1));
                        return(true);
                    }

                    if (target.Ignored.Contains(Name))
                    {
                        SendPacket(new DirectPushError(2));
                        return(true);
                    }

                    SendPacket(new DirectPushError(0));
                    server.SendPacket(target, new ServerDirectPush(this, push));

                    return(true);

                case AresId.MSG_CHAT_CLIENT_BROWSE:
                    SendPacket(new BrowseError(((Browse)e.Packet).BrowseId));
                    return(true);

                case AresId.MSG_CHAT_CLIENT_SEARCH:
                    SendPacket(new SearchEnd(((Search)e.Packet).SearchId));
                    return(true);

                case AresId.MSG_CHAT_CLIENTCOMPRESSED: {
                    Compressed packet  = (Compressed)e.Packet;
                    byte[]     payload = Zlib.Decompress(packet.Data);

                    var reader = new PacketReader(payload)
                    {
                        Position = 0L
                    };

                    while (reader.Remaining >= 3)
                    {
                        ushort count = reader.ReadUInt16();
                        byte   id    = reader.ReadByte();

                        IPacket msg = Socket.Formatter.Unformat(id, reader.ReadBytes(count));
                        OnPacketReceived(Socket, new PacketEventArgs(msg, WebSocketMessageType.Binary, 0));
                    }
                    break;
                }

                default:
                    break;
                }

                return(false);//wasn't handled
            }
            else
            {
                //not captcha, not logged, error?
                Logging.Info("AresClient", "Client {0} sent {1} before logging in.", this.ExternalIp, e.Packet.Id);
                return(true);
            }
        }
 public async Task<ClientUpdate.response> ClientUpdate(ClientUpdate.request request, CancellationToken? token = null)
 {
     return await SendAsync<ClientUpdate.response>(request.ToXmlString(), token.GetValueOrDefault(CancellationToken.None));
 }
        } // getClient

        protected override Client updateClient(ClientUpdate client)
        {
            var actionResult = controller_.PutClient(client.Id, client);

            return(decodeActionResult <Client>(actionResult));
        } // updateClient
Example #33
0
        } // getClient

        protected override Client updateClient(ClientUpdate client)
        {
            return(repo_.Update(client));
        } // updateClient