public async Task <IActionResult> Patch(
            [FromBody] JsonPatchDocument <LoverCloudUserUpdateResource> patchDoc)
        {
            LoverCloudUser user = await _repository.FindByIdAsync(this.GetUserId());

            //AuthorizationResult result = await _authorizationService
            //    .AuthorizeAsync(User, null, new SameUserRequirement(user.Id));
            //if (!result.Succeeded) return Forbid();

            if (user == null)
            {
                return(BadRequest("无法获得用户信息"));
            }

            LoverCloudUserUpdateResource userUpdateResource =
                _mapper.Map <LoverCloudUserUpdateResource>(user);

            patchDoc.ApplyTo(userUpdateResource);
            _mapper.Map(userUpdateResource, user);

            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("保存数据失败");
            }

            return(NoContent());
        }
        public async Task <IActionResult> Login([FromQuery] string fields)
        {
            string id = this.GetUserId();

            LoverCloudUser user = await _repository.FindByIdAsync(id);

            var userResource = _mapper.Map <LoverCloudUserResource>(user);

            if (userResource.Spouse != null)
            {
                userResource.Spouse.Spouse = null;
            }

            userResource.GetProfileImageUrl(Url);
            if (userResource.Spouse != null)
            {
                userResource.Spouse.GetProfileImageUrl(Url);
                userResource.Spouse.LoverAlbumCount = userResource.LoverAlbumCount = await _albumRepository.CountAsync(user.Lover.Id);

                userResource.Spouse.LoverLogCount = userResource.LoverLogCount = await _logRepository.CountAsync(user.Lover.Id);

                userResource.Spouse.LoverAnniversaryCount = userResource.LoverAnniversaryCount = await _anniversaryRepository.CountAsync(user.Lover.Id);
            }

            var shapedUserResource = userResource.ToDynamicObject(fields?.Contains("spouse,") ?? false  ? fields.Replace("spouse,", ""):fields);

            if (userResource.Spouse != null)
            {
                (shapedUserResource as IDictionary <string, object>).Add("spouse", userResource.Spouse.ToDynamicObject(
                                                                             $"sex, userName, birth, id, profileImageUrl"));
            }

            return(Ok(shapedUserResource));
        }
示例#3
0
        public async Task <IActionResult> Add(
            [FromBody] LoverAnniversaryAddResource addResource)
        {
            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            LoverCloudUser user = await _userRepository.FindByIdAsync(this.GetUserId());

            if (user.Lover == null)
            {
                return(this.UserNoLoverResult(user));
            }

            LoverAnniversary anniversary = _mapper.Map <LoverAnniversary>(addResource);

            anniversary.Lover = user.Lover;
            _anniversaryRepository.Add(anniversary);

            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("Failed to add anniversary");
            }

            ExpandoObject anniversaryResource = _mapper.Map <LoverAnniversaryResource>(anniversary)
                                                .ToDynamicObject();

            (anniversaryResource as IDictionary <string, object>).Add(
                "links", CreateLinksForAnniversary(anniversary.Id));

            return(CreatedAtRoute("AddLoverAnniversary", anniversaryResource));
        }
        private async Task SaveProfileImageAsync(IFormFile profile, LoverCloudUser user)
        {
            if (profile == null || user == null)
            {
                return;
            }
            // 完整的文件保存路径
            var physicalPath = user.GenerateProfileImagePhysicalPath(
                profile.GetFileSuffix());
            // 删除之前的头像
            var dir = Path.GetDirectoryName(physicalPath);

            if (Directory.Exists(dir))
            {
                foreach (string file in Directory.EnumerateFiles(dir))
                {
                    System.IO.File.Delete(file);
                }
            }

            // 保存上传的文件
            await profile.SaveToFileAsync(physicalPath);

            user.ProfileImagePhysicalPath = physicalPath;
        }
        public async Task <IActionResult> Delete([FromRoute] string id)
        {
            string         userId = this.GetUserId();
            LoverCloudUser user   = await _userRepository.FindByIdAsync(userId);

            MenstruationLog mlog = await _mlogRepository.FindByIdAsync(
                id, x => x.Include(l => l.LoverCloudUser)
                .Include(l => l.MenstruationDescriptions));

            if (mlog == null)
            {
                return(NotFound());
            }
            if (mlog?.LoverCloudUser?.Sex == Sex.Male ||
                mlog.LoverCloudUser?.Id != this.GetUserId())
            {
                return(Forbid());
            }

            _mlogRepository.Delete(mlog);

            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("Failed to delete resource");
            }

            return(NoContent());
        }
        public async Task <IActionResult> Add([FromBody] MenstruationLogAddResource addResource)
        {
            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            LoverCloudUser user = await _userRepository.FindByIdAsync(this.GetUserId());

            MenstruationLog mlog = _mapper.Map <MenstruationLog>(addResource);

            mlog.LoverCloudUser = user;
            _mlogRepository.Add(mlog);
            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("Failed to add menstruation log.");
            }

            MenstruationLogResource mlogResource = _mapper.Map <MenstruationLogResource>(mlog);
            ExpandoObject           result       = mlogResource.ToDynamicObject()
                                                   .AddLinks(this, null, "menstruation_log", null,
                                                             "DeleteMenstruationLog", "PartiallyUpdateMenstruationLog");

            return(CreatedAtRoute("AddMenstruationLog", result));
        }
        public async Task <IActionResult> Get(
            [FromRoute] string menstruationLogId,
            [FromQuery] MenstruationDescriptionParameters parameters)
        {
            LoverCloudUser user = await _userRepository.FindByIdAsync(
                this.GetUserId());

            if (user.Sex == Sex.Male)
            {
                return(Forbid());
            }

            PaginatedList <MenstruationDescription> descriptions =
                await _mdescriptionRepository.GetAsync(
                    user.Id, menstruationLogId, parameters);

            IEnumerable <MenstruationDescriptionResource> descriptionResources =
                _mapper.Map <IEnumerable <MenstruationDescriptionResource> >(descriptions);

            IEnumerable <ExpandoObject> shapedDescriptionResources =
                descriptionResources.ToDynamicObject(parameters.Fields);

            var result = new
            {
                value = shapedDescriptionResources,
                links = this.CreatePaginationLinks(
                    "GetMenstruationDescriptions", parameters,
                    descriptions.HasPrevious, descriptions.HasNext)
            };

            this.AddPaginationHeaderToResponse(descriptions);

            return(Ok(result));
        }
示例#8
0
        public async Task <IActionResult> Add([FromBody] LoverAlbumAddResource addResource)
        {
            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            LoverCloudUser user = await GetUserAsync();

            //if (user.Lover == null) return UserNoLoverResult(user);

            LoverAlbum album = _mapper.Map <LoverAlbum>(addResource);

            album.Creater = user;
            album.Lover   = user.Lover;

            _albumRepository.Add(album);
            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("Failed to save changes");
            }

            LoverAlbumResource albumResource = _mapper.Map <LoverAlbumResource>(album);

            ExpandoObject shapedAlbumResource = albumResource.ToDynamicObject()
                                                .AddLinks(this, null, "album", "GetLoverAlbum", "DeleteLoverAlbum", "PartiallyUpdateLoverAlbum");

            return(CreatedAtRoute("AddLoverAlbum", shapedAlbumResource));
        }
示例#9
0
        public async Task <IActionResult> Add([FromForm] LoverPhotoAddResource loverPhotoAddResource)
        {
            IFormFile file = loverPhotoAddResource.File;

            if (file == null)   // 表单中必须包含图片文件
            {
                ModelState.AddModelError("loverPhotoAddResource", $"parameter {file} cannot be null");
                return(BadRequest(ModelState));
            }

            // 无法自动映射表单的Tags到对应的Tags集合属性, 所以手动处理一下, 读取key为Tags的值, 反序列化json
            // 元数据是json数组, 示例: [{"name": "value"}, {"name", "value2"}]
            // 表单中只能有一个tags键
            Request.Form.TryGetValue("tags", out StringValues tagsStrings);
            if (tagsStrings.Count > 1)
            {
                return(BadRequest());
            }
            if (tagsStrings.Count <= 0)
            {
                tagsStrings = new StringValues("[]");
            }
            IList <TagAddResource> tags =
                JsonConvert.DeserializeObject <IList <TagAddResource> >(tagsStrings.FirstOrDefault());

            loverPhotoAddResource.Tags = tags;

            LoverCloudUser user = await _userRepository.FindByIdAsync(this.GetUserId());

            Lover lover = user.Lover;

            LoverPhoto loverPhoto = _mapper.Map <LoverPhoto>(loverPhotoAddResource);

            // 生成 PhotoPhysicalPath 要用到 Uploader, 所以先设置 Uploader 的值
            loverPhoto.Uploader     = user;
            loverPhoto.Lover        = lover;
            loverPhoto.PhysicalPath = loverPhoto.GeneratePhotoPhysicalPath(file.GetFileSuffix());;
            loverPhoto.UpdateDate   = DateTime.Now;
            loverPhoto.PhotoUrl     = Url.LinkRelative("GetPhoto", new { id = loverPhoto.Id });
            // 添加到数据库
            _repository.Add(loverPhoto);
            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("数据保存失败");
            }
            // 保存图片文件
            await file.SaveToFileAsync(loverPhoto.PhysicalPath);

            LoverPhotoResource loverPhotoResource = _mapper.Map <LoverPhotoResource>(loverPhoto);
            ExpandoObject      result             = loverPhotoResource.ToDynamicObject()
                                                    .AddLinks(this, null, "photo", "GetPhoto", "DeleteLoverPhoto", "PartiallyUpdateLoverPhoto");

            return(CreatedAtRoute("AddLoverPhoto", result));
        }
        protected override async Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            MustFemaleRequirement requirement)
        {
            LoverCloudUser user = await _userRepository.FindByIdAsync(context.User.GetUserId());

            if (user != null && user.Sex == Sex.Female)
            {
                context.Succeed(requirement);
            }
        }
        public async Task <IActionResult> GetById([FromRoute] string id)
        {
            LoverCloudUser user = await _repository.FindByIdAsync(id);

            LoverCloudUserResource userResource = _mapper.Map <LoverCloudUserResource>(user);

            userResource.GetProfileImageUrl(Url);

            ExpandoObject shapedUser = userResource.ToDynamicObject("id, profileImageUrl, username");

            return(Ok(shapedUser));
        }
        public async Task <IActionResult> PostProfileImage([FromForm] IFormFile profileImage)
        {
            LoverCloudUser user = await _repository.FindByIdAsync(this.GetUserId());

            if (user == null)
            {
                return(BadRequest("无法获得用户信息"));
            }
            await SaveProfileImageAsync(profileImage, user);

            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("保存数据失败");
            }
            return(PhysicalFile(user.ProfileImagePhysicalPath, "image/png"));
        }
        public async Task <IActionResult> Add([FromForm] LoverLogAddResource addResource)
        {
            LoverCloudUser user = await _userRepository.FindByIdAsync(this.GetUserId());

            Lover lover = user.Lover;

            LoverLog loverLog = _mapper.Map <LoverLog>(addResource);

            loverLog.Creater        = user;
            loverLog.Lover          = lover;
            loverLog.CreateDateTime = DateTime.Now;
            loverLog.LastUpdateTime = DateTime.Now;
            _repository.Add(loverLog);
            if (addResource.Photos != null)
            {
                foreach (var formFile in addResource.Photos)
                {
                    var photo = new LoverPhoto
                    {
                        Name           = formFile.FileName,
                        Uploader       = user,
                        Lover          = lover,
                        LoverLog       = loverLog,
                        PhotoTakenDate = DateTime.Now,
                    };
                    photo.PhysicalPath = photo.GeneratePhotoPhysicalPath(formFile.GetFileSuffix());
                    loverLog.LoverPhotos.Add(photo);
                    await formFile.SaveToFileAsync(photo.PhysicalPath);
                }
            }

            if (!await _unitOfWork.SaveChangesAsync())
            {
                return(NoContent());
            }

            LoverLogResource loverLogResource       = _mapper.Map <LoverLogResource>(loverLog);
            ExpandoObject    shapedLoverLogResource = loverLogResource.ToDynamicObject()
                                                      .AddLinks(
                this, null, "log", "GetLoverLog",
                "DeleteLoverLog", "PartiallyUpdateLoverLog");

            return(CreatedAtRoute("AddLoverLog", shapedLoverLogResource));
        }
        public async Task <IActionResult> GetProfileImage([FromRoute] string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return(BadRequest("user id not assigned"));
            }
            //string loggedUserId = this.GetUserId();
            LoverCloudUser user = await _repository.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"找不到id为 {userId} 的用户"));
            }

            if (string.IsNullOrEmpty(user.ProfileImagePhysicalPath) ||
                !System.IO.File.Exists(user.ProfileImagePhysicalPath))
            {
                return(NotFound($"用户 {user} 还没有上传头像"));
            }

            return(PhysicalFile(user.ProfileImagePhysicalPath, "image/png"));
        }
示例#15
0
        public async Task <IActionResult> PatchLoverRequest([FromRoute] string id, [FromBody] JsonPatchDocument <LoverRequestUpdateResource> loverRequestPatchDocument)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(BadRequest());
            }

            var loverRequestToUpdate = await _repository.FindByIdAsync(id);

            if (loverRequestToUpdate == null)
            {
                return(BadRequest($"找不到对应的 LoverRequest({id})"));
            }

            AuthorizationResult authorizationResult = await _authorizationService
                                                      .AuthorizeAsync(
                User,
                null,
                new SameUserRequirement(loverRequestToUpdate.ReceiverId));

            if (!(authorizationResult.Succeeded))
            {
                return(Forbid());
            }

            var loverRequestToUpdateResource = _mapper.Map <LoverRequestUpdateResource>(
                loverRequestToUpdate);

            loverRequestPatchDocument.ApplyTo(loverRequestToUpdateResource);
            _mapper.Map(loverRequestToUpdateResource, loverRequestToUpdate);

            //if (loverRequestToUpdate.LoverId != null) return BadRequest();

            if (loverRequestToUpdateResource.Succeed == true &&
                loverRequestToUpdate.LoverId == null &&
                loverRequestToUpdate.Receiver.Lover == null &&
                loverRequestToUpdate.Requester.Lover == null)
            {
                var users = new LoverCloudUser[]
                {
                    loverRequestToUpdate.Receiver,
                    loverRequestToUpdate.Requester
                };

                var lover = new Lover
                {
                    RegisterDate    = DateTime.Now,
                    LoverCloudUsers = users
                };
                loverRequestToUpdate.Lover = lover;
                _loverRepository.Add(lover);
            }
            else
            {
                return(BadRequest());
            }

            if (!await _unitOfWork.SaveChangesAsync())
            {
                throw new Exception("保存数据到数据库失败");
            }

            return(NoContent());
        }
 public static IActionResult UserNoLoverResult(
     this ControllerBase contorllerBase, LoverCloudUser user) =>
 contorllerBase.Forbid($"用户 {user?.ToString()??string.Empty} 还没有情侣, 无法操作资源");