Example #1
0
        public override AnswerItem Reply(MessageItem mItem)
        {
            if (mItem.UserId != _adminUser)
            {
                return(new AnswerItem {
                    Message = "Access denied."
                });
            }

            if (string.IsNullOrEmpty(mItem.TextOnly))
            {
                return new AnswerItem {
                           Message = "Give me a file name to update."
                }
            }
            ;

            var fileName = mItem.Text;
            var filePath = Path.Combine(_preInstalledFolderPath, fileName);

            if (!fileName.EndsWith(Extension))
            {
                return new AnswerItem {
                           Message = "It is not a csv file."
                }
            }
            ;
            if (!File.Exists(filePath))
            {
                return new AnswerItem {
                           Message = "No such file."
                }
            }
            ;

            var serviceFolders = _repository.GetUserFolders(_serverUserId);

            ThreadPool.QueueUserWorkItem(cb =>
            {
                var resultString = new StringBuilder();

                fileName          = Path.GetFileNameWithoutExtension(filePath);
                var serviceFolder = serviceFolders.FirstOrDefault(a => a.Name == fileName);
                if (serviceFolder != null)
                {
                    _repository.DeleteFolder(serviceFolder.Id);
                    resultString.AppendLine("Old folder was removed.");
                }

                var fileBody = File.ReadAllBytes(filePath);

                var lines  = BytesToLines(fileBody);
                var result = _parseProvider.ImportWords(lines);

                //OwnerId will be taken from cookies, so we may not to specify it here
                var idFolder = _repository.AddFolder(new Folder {
                    Name = fileName, OwnerId = _serverUserId
                });
                _repository.SetCurrentFolder(_serverUserId, idFolder);
                var uploadWords = UploadWords(result, _serverUserId);

                resultString.AppendLine(uploadWords.SuccessfulWords.Any()
                    ? $"Words from folder {fileName} have been added."
                    : $"Can't add words to {fileName} folder.");

                _tClient.SendTextMessageAsync(mItem.ChatId, resultString.ToString(), ParseMode.Default, true, false, 0,
                                              new ReplyKeyboardRemove());
            });

            return(new AnswerItem {
                Message = "Import is running..."
            });
        }
    }
}