public async Task <IActionResult> CreatePost(PostCreateDTO postCreateDTO) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(User.Identity.Name); var categories = await _categoryService.GetAllAsync(); var languages = await _languageService.GetAllAsync(); var category = categories.First(); var language = languages.First(); var post = _mapper.Map <Post>(postCreateDTO); post.UserId = user.Id; post.Created = DateTime.Now; post.CreatedBy = user.UserName; post.PostStatus = PostStatus.Posted; post.CategoryId = category.Id; post.LanguageId = language.Id; var newPost = await _postService.CreateAsync(post); if (postCreateDTO.Files != null) { List <Picture> pictures = AddFiles(postCreateDTO.Files, newPost.Id, user.UserName); foreach (var picture in pictures) { await _pictureService.CreateAsync(picture); } } var usersForNotification = await _userService.GetUsersForNitificationAsync(); if (usersForNotification != null) { var usersVoewDTO = _mapper.Map <List <UserViewDto> >(usersForNotification); var postViewDTO = _mapper.Map <PostViewDTO>(post); var userViewDTO = _mapper.Map <UserViewDto>(user); postViewDTO.UserViewDto = userViewDTO; var viewPostLink = Url.Action( "PostDetails", "Post", new { id = postViewDTO.Id }, protocol: HttpContext.Request.Scheme); var stringForm = await _razorViewToStringRenderer.RenderToStringAsync("Post/PostForEmailNotification", postViewDTO); await _automaticEmailNotificationService.SentAutomaticNotificationAsync(EmailNotificationSettings.subject, EmailNotificationSettings.CteateMessage(postViewDTO, stringForm, viewPostLink), usersVoewDTO); } return(RedirectToAction("Index", "Home")); } return(View(postCreateDTO)); }
public async Task <IActionResult> Create(IFormFile picture, [FromForm] CreatePictureRequest createPictureRequest) { if (!ModelState.IsValid) { return(BadRequest()); } var userId = HttpContext?.User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value; var result = await _pictureService.CreateAsync(picture, userId, createPictureRequest); return(Ok(result)); }
public async Task <TPrimaryKey> CreateAsync(IFormFileCollection attachments, PostDto dto) { var isPostingAllowed = await _banService.IsPostingAllowedAsync(dto.ThreadId, dto.UserIpAddress); if (!isPostingAllowed.Item1) { throw new HttpResponseException(HttpStatusCode.Forbidden, isPostingAllowed.Item2); } else if (attachments == null) { return(await CreateAsync(dto, (post) => { post.Thread = Context.Threads.FirstOrDefault(thread => thread.Id == dto.ThreadId); })); } else { var postId = await CreateAsync(dto, (post) => { post.Thread = Context.Threads.FirstOrDefault(thread => thread.Id == dto.ThreadId); }); try { var containerName = dto.ThreadId.ToString(); if (string.IsNullOrWhiteSpace(containerName)) { throw new Exception($"{nameof(containerName)} is null or whitespace"); } foreach (var attachment in attachments) { string blobName; var attachmentParentDto = _attachmentCategorizer.CreateAttachmentDto(attachment.FileName); attachmentParentDto.PostId = postId; attachmentParentDto.FileExtension = Path.GetExtension(attachment.FileName)?.TrimStart('.'); attachmentParentDto.FileName = Path.GetFileNameWithoutExtension(attachment.FileName); attachmentParentDto.Size = attachment.Length; attachmentParentDto.Hash = _cryptoService.HashHex(attachment.OpenReadStream()); if (attachmentParentDto is AudioDto audioDto) { blobName = (await _audioService.CreateAsync(audioDto, entity => { entity.Post = Context.Posts.FirstOrDefault(post => post.Id == postId); })).ToString(); } else if (attachmentParentDto is PictureDto pictureDto) { if (_attachmentCategorizer.IsPictureExtensionSupported(pictureDto.FileExtension)) { // generate thumbnail if such file extension is supported var image = Image.Load(attachment.OpenReadStream()); pictureDto.Width = image.Width; pictureDto.Height = image.Height; blobName = (await _pictureService.CreateAsync(pictureDto, entity => { entity.Post = Context.Posts.FirstOrDefault(post => post.Id == postId); })).ToString(); var thumbnail = _thumbnailGenerator.GenerateThumbnail( image, _hikkabaConfiguration.ThumbnailsMaxWidth, _hikkabaConfiguration.ThumbnailsMaxHeight); await _storageProvider.SaveBlobStreamAsync( containerName + Defaults.ThumbnailPostfix, blobName, thumbnail.Image); } else { // otherwise save the same image as thumbnail blobName = (await _pictureService.CreateAsync(pictureDto, entity => { entity.Post = Context.Posts.FirstOrDefault(post => post.Id == postId); })).ToString(); await _storageProvider.SaveBlobStreamAsync( containerName + Defaults.ThumbnailPostfix, blobName, attachment.OpenReadStream()); } } else if (attachmentParentDto is VideoDto videoDto) { blobName = (await _videoService.CreateAsync(videoDto, entity => { entity.Post = Context.Posts.FirstOrDefault(post => post.Id == postId); })).ToString(); } else if (attachmentParentDto is DocumentDto documentDto) { blobName = (await _documentService.CreateAsync(documentDto, entity => { entity.Post = Context.Posts.FirstOrDefault(post => post.Id == postId); })).ToString(); } else { throw new Exception($"Unknown attachment type: {attachmentParentDto.GetType().Name}"); } if (string.IsNullOrWhiteSpace(blobName)) { throw new Exception($"{nameof(blobName)} is null or whitespace"); } await _storageProvider.SaveBlobStreamAsync(containerName, blobName, attachment.OpenReadStream()); } } catch (Exception ex) { _logger.LogError(ex + $" Post {postId} will be deleted."); await DeleteAsync(postId); throw; } return(postId); } }
public async Task <IActionResult> Update(UserUpdateDto userUpdateDto, List <string> roles) { if (ModelState.IsValid) { try { var user = await _userManager.FindByIdAsync(userUpdateDto.Id.ToString()); if (userUpdateDto.Avatar != null) { // Get the user's prifile picture var currentAvatar = await _pictureService.GetAvatarAsync(user.Id); Picture avatar = new Picture(); if (currentAvatar != null) { // Delete the current profile pictures await _pictureService.DeleteAsync(currentAvatar.Id); System.IO.File.Delete(currentAvatar.Path); } AddAvatar(userUpdateDto.Avatar, user.Id, out avatar); await _pictureService.CreateAsync(avatar); } if (user != null) { user.UserName = userUpdateDto.UserName; user.Email = userUpdateDto.Email; user.FacebookLink = userUpdateDto.FacebookLink; user.InstagramLink = userUpdateDto.InstagramLink; user.LinkedInLink = userUpdateDto.LinkedInLink; user.TwitterLink = userUpdateDto.TwitterLink; user.YoutubeLink = userUpdateDto.YoutubeLink; user.AutomaticEmailNotification = userUpdateDto.AutomaticEmailNotification; } if (User.IsInRole("SuperAdmin")) { // получем список ролей пользователя var userRoles = await _userManager.GetRolesAsync(user); // получаем все роли var allRoles = _roleManager.Roles.ToList(); // получаем список ролей, которые были добавлены var addedRoles = roles.Except(userRoles); // получаем роли, которые были удалены var removedRoles = userRoles.Except(roles); await _userManager.AddToRolesAsync(user, addedRoles); await _userManager.RemoveFromRolesAsync(user, removedRoles); } await _userManager.UpdateAsync(user); } catch (DbUpdateException ex) { return(Content(ex.Message)); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); } if (User.IsInRole("SuperAdmin")) { return(RedirectToAction("Users", "Admin")); } return(RedirectToAction("Index", "Home")); } return(View(userUpdateDto)); }