/// <summary>
        /// get user DB model by user account,
        /// if not in cache, then will get the new model,
        /// if null, then cache too
        /// </summary>
        /// <param name="id"></param>
        /// <param name="includeAvatar">is need include avatar</param>
        /// <returns></returns>
        internal static async Task <DB.Tables.User> GetUserModelAsync(string account, bool includeAvatar = false)
        {
            string key = USER_CACHE_KEY + account;

            (bool hasValue, DB.Tables.User value) = Cache.TryGet <DB.Tables.User>(key);
            using var db = new LOPDbContext();

            if (hasValue)
            {
                if (includeAvatar)
                {
                    if (value.Avatar != null)
                    {
                        return(value);
                    }
                    value = await db.Users.AsNoTracking().Include(user => user.Avatar).FirstOrDefaultAsync(user => user.Account == account);

                    Cache.Set(key, value, Default_Cache_Time);
                }
                return(value);
            }
            else
            {
                if (includeAvatar)
                {
                    value = await db.Users.AsNoTracking().Include(user => user.Avatar).FirstOrDefaultAsync(user => user.Account == account);
                }
                else
                {
                    value = await db.Users.AsNoTracking().FirstOrDefaultAsync(user => user.Account == account);
                }
                Cache.Set(key, value, Default_Cache_Time);
            }
            return(value);
        }
Example #2
0
        /// <summary>
        /// modify the user email
        /// </summary>
        /// <returns></returns>
        public virtual async Task <(bool, string)> ModifyPasswordAsync(Models.ChangePassword model)
        {
            await using var db = new LOPDbContext();
            DB.Tables.User user = await db.Users.AsNoTracking().FirstOrDefaultAsync(user => user.Id == Id && user.Password.Equals(model.OldPassword, StringComparison.OrdinalIgnoreCase));

            if (user is null)
            {
                return(false, "旧密码错误");
            }

            if (string.IsNullOrWhiteSpace(model.NewPassword))
            {
                return(false, "密码不能为空");
            }

            if (user.Password == model.NewPassword)
            {
                return(true, "");
            }
            user.Password = model.NewPassword;
            db.Update(user);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount == 1)
            {
                UserCache.SetUserModel(user);
                return(true, "");
            }
            throw new Exception("修改密码失败");
        }
Example #3
0
        /// <summary>
        /// 发布新通知
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <(bool, string)> PostNowNotificationAsync(Models.NewNotification model)
        {
            if (string.IsNullOrWhiteSpace(model.Title))
            {
                return(false, "标题不能位空");
            }
            if (string.IsNullOrWhiteSpace(model.Content))
            {
                return(false, "内容不能位空");
            }
            DB.Tables.Notification notification = new DB.Tables.Notification
            {
                Title   = model.Title,
                Content = model.Content,
                IsTop   = model.IsTop
            };
            await using var db = new LOPDbContext();
            db.Notifications.Add(notification);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount == 1)
            {
                return(true, "");
            }
            throw new Exception("发布通知失败");
        }
Example #4
0
        /// <summary>
        /// 修改博文
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task ModifyAsync(Models.ModifyPost model)
        {
            var targetIds = await Targets.AppendTargetsAsync(model.Targets);

            _blog.Title     = model.Title;
            _blog.TargetIds = string.Join(',', targetIds);
            _blog.Content   = model.Content;
            if (_blog.State == (int)BlogState.Disabled)
            {
                _blog.State = (int)BlogState.Audit;
            }

            var author = _blog.Author;

            _blog.Author = null;

            await using var db = new LOPDbContext();
            db.Blogs.Update(_blog);
            int changeConut = await db.SaveChangesAsync();

            if (changeConut != 1)
            {
                throw new Exception("修改博文出现错误");
            }
            _blog.Author = author;
        }
Example #5
0
        /// <summary>
        /// get administrator by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <Administrator> GetAdministratorAsync(int id)
        {
            await using var db = new LOPDbContext();
            var user = await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == id);

            return(ParseAdministrator(user));
        }
Example #6
0
        /// <summary>
        /// 获取通知列表
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        public async Task <Paginator> GetListAsync(Paginator pager)
        {
            string s = pager["s"] ?? "";

            Expression <Func <DB.Tables.Notification, bool> > whereStatement = n => true;

            if (!string.IsNullOrWhiteSpace(s))
            {
                whereStatement = whereStatement.And(n => n.Title.Contains(s));
            }

            await using var db = new LOPDbContext();
            pager.TotalSize    = await db.Notifications.CountAsync(whereStatement);

            pager.List = await db.Notifications.AsNoTracking()
                         .OrderByDescending(n => n.IsTop)
                         .ThenByDescending(n => n.CreateDate)
                         .Where(whereStatement)
                         .Skip(pager.Skip)
                         .Take(pager.Size)
                         .Select(n => new Results.NotificationItem
            {
                Id       = n.Id,
                Title    = n.Title,
                DateTime = n.CreateDate.ToString("yyyy/MM/dd HH:mm"),
                IsTop    = n.IsTop
            })
                         .ToListAsync();

            return(pager);
        }
        public async Task <string[]> GetTargetsNameAsync(int[] targetIds)
        {
            await using var db = new LOPDbContext();

            List <DB.Tables.Target> list = await db.Targets.AsNoTracking()
                                           .Where(t => targetIds.Contains(t.Id))
                                           .ToListAsync();

            return(list.Select(t => t.Name).ToArray());
        }
Example #8
0
        /// <summary>
        /// modify the user avatar
        /// </summary>
        /// <returns>(bool: isSuccessfully, string: message when fault or avatar request path when successfully)</returns>
        public virtual async Task <(bool, string)> ModifyAvatarAsync(int avatarId)
        {
            await using var db = new LOPDbContext();
            DB.Tables.User user = await db.Users.AsNoTracking().Include(user => user.Avatar).FirstOrDefaultAsync(user => user.Id == Id);

            if (user is null)
            {
                return(false, "该用户不存在");
            }
            if (user.AvatarId == avatarId)
            {
                return(true, "");
            }

            DB.Tables.File SOURCE_AVATAR     = user.Avatar;
            int            shouldChangeCount = 2;

            //  删除原头像
            if (user.AvatarId != AVATAR_DEFAULT_ID && user.Avatar != null)
            {
                db.Files.Remove(SOURCE_AVATAR);
                shouldChangeCount++;
            }

            //  user.AvatarId = avatarId;
            var avatarModel = await db.Files.AsNoTracking().FirstOrDefaultAsync(file => file.Id == avatarId);

            if (avatarModel == null)
            {
                return(false, "该头像不存在");
            }

            user.Avatar = avatarModel;
            db.Users.Update(user);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount == shouldChangeCount)
            {
                if (SOURCE_AVATAR.Id != AVATAR_DEFAULT_ID)
                {
                    //  删除原头像文件
                    Files.File.Delete(SOURCE_AVATAR.SaveName);
                    //  删除缩略图
                    Files.File.DeleteThumbnail(SOURCE_AVATAR.Thumbnail);
                }
                //  缓存用户更新后的数据
                UserCache.SetUserModel(user);
                //  返回新头像的访问路径
                string saveWebPath = Config.GetValue("File:SaveWebPath");
                saveWebPath = Path.Combine(saveWebPath, avatarModel.SaveName);
                return(true, saveWebPath);
            }
            throw new Exception("修改头像失败");
        }
Example #9
0
        /// <summary>
        /// get client by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <Client> GetClientAsync(int id)
        {
            await using var db = new LOPDbContext();
            var user = await db.Users.AsNoTracking().Include(u => u.Avatar).FirstOrDefaultAsync(u => u.Id == id);

            if (user is null)
            {
                throw new Exception($"{user} 不是客户");
            }
            //  管理员也是客户
            return(ParseClient(user));
        }
Example #10
0
        public async Task <Blog> GetBlogAsync(int id)
        {
            await using var db = new LOPDbContext();
            var blogModel = await db.Blogs.AsNoTracking()
                            .Include(b => b.Author)
                            .FirstOrDefaultAsync(blog => blog.Id == id);

            if (blogModel is null)
            {
                return(null);
            }
            return(new Blog(blogModel));
        }
Example #11
0
        /// <summary>
        /// 获取通知详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <Results.NotificationDetail> GetNotificitionDetailAsync(int id)
        {
            await using var db = new LOPDbContext();
            var notification = await db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == id);

            if (notification is null)
            {
                return(null);
            }
            return(new Results.NotificationDetail
            {
                Title = notification.Title,
                Content = notification.Content
            });
        }
        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="blogId"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        public async Task AddComment(int blogId, string content, int?commenter)
        {
            await using var db = new LOPDbContext();
            DB.Tables.Comment newComment = new DB.Tables.Comment
            {
                BlogId      = blogId,
                Content     = content,
                CommenterId = commenter
            };
            db.Comments.Add(newComment);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount != 0)
            {
                throw new Exception("评论失败");
            }
        }
Example #13
0
        /// <summary>
        /// 点赞
        /// </summary>
        /// <returns></returns>
        public async Task LikeAsync()
        {
            _blog.Likes++;
            var author = _blog.Author;

            _blog.Author = null;

            await using var db = new LOPDbContext();
            db.Blogs.Update(_blog);
            int changeConut = await db.SaveChangesAsync();

            if (changeConut != 1)
            {
                throw new Exception("点赞发生错误");
            }
            _blog.Author = author;
        }
Example #14
0
        /// <summary>
        /// save file info to DB
        /// </summary>
        /// <param name="fileInfo">file info</param>
        /// <returns>id of file in DB</returns>
        public static async Task <(bool, int)> SaveToDBAsync(string fileName, string saveName, long size)
        {
            await using var db = new LOPDbContext();
            DB.Tables.File newFileModel = new DB.Tables.File
            {
                Name      = fileName,
                SaveName  = saveName,
                Extension = Path.GetExtension(fileName),
                Size      = size
            };

            await db.AddAsync(newFileModel);

            bool success = await db.SaveChangesAsync() == 1;

            return(success, success ? newFileModel.Id : -1);
        }
Example #15
0
        /// <summary>
        /// 删除一个通知
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteNotificationAsync(int id)
        {
            await using var db = new LOPDbContext();
            var notification = await db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == id);

            if (notification is null)
            {
                return;
            }
            db.Notifications.Remove(notification);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount != 1)
            {
                throw new Exception("删除一个通知失败");
            }
        }
        public async Task <Paginator> GetListAsync(Paginator pager)
        {
            string s = pager["s"] ?? "";

            if (s.Length > SEARCH_MAX_LENGTH)
            {
                s = s.Substring(0, SEARCH_MAX_LENGTH);
            }

            Expression <Func <DB.Tables.Blog, bool> > whereStatement = blog => blog.State == (int)Blog.BlogState.Enabled;
            var searchStatement = WhereExpression(s);

            if (searchStatement != null)
            {
                whereStatement = whereStatement.And(searchStatement);
            }

            await using var db = new LOPDbContext();
            pager.TotalSize    = await db.Blogs.CountAsync(whereStatement);

            pager.List = await db.Blogs.AsNoTracking()
                         .OrderByDescending(blog => blog.Likes)
                         .ThenByDescending(blog => blog.CreateDate)
                         .Where(whereStatement)
                         .Skip(pager.Skip)
                         .Take(pager.Size)
                         .Include(blog => blog.Author)
                         .Select(blog => new Results.BlogItem
            {
                Id            = blog.Id,
                Title         = blog.Title,
                Author        = blog.Author.Name,
                AuthorAccount = blog.Author.Account,
                DateTime      = blog.CreateDate.ToString("yyyy/MM/dd HH:mm"),
                Views         = blog.Views,
                Likes         = blog.Likes,
                State         = KeyValue.Create(blog.State, blog.State.GetDescription <Blog.BlogState>())
            })
                         .ToListAsync();

            return(pager);
        }
Example #17
0
        public async Task <Paginator> GetListAsync(Paginator pager)
        {
            string account = pager["account"] ?? throw new ArgumentNullException("需要用户");
            Expression <Func <DB.Tables.Blog, bool> > whereStatement = blog => blog.Author.Account.Equals(account, StringComparison.OrdinalIgnoreCase);
            string s = pager["s"] ?? "";

            if (!string.IsNullOrWhiteSpace(s))
            {
                whereStatement = whereStatement.And(blog => blog.Title.Contains(s));
            }

            if (int.TryParse(pager["state"], out int state))
            {
                whereStatement = whereStatement.And(blog => blog.State == state);
            }

            await using var db = new LOPDbContext();
            pager.TotalSize    = await db.Blogs.CountAsync(whereStatement);

            var list = await db.Blogs.AsNoTracking()
                       .OrderByDescending(blog => blog.CreateDate)
                       .Where(whereStatement)
                       .Include(blog => blog.Author)
                       .Skip(pager.Skip)
                       .Take(pager.Size)
                       .Select(blog => new Results.BlogItem
            {
                Id            = blog.Id,
                Title         = blog.Title,
                Author        = blog.Author.Name,
                AuthorAccount = blog.Author.Account,
                DateTime      = blog.CreateDate.ToString("yyyy/MM/dd HH:mm"),
                Views         = blog.Views,
                Likes         = blog.Likes,
                State         = KeyValue.Create(blog.State, blog.State.GetDescription <Blog.BlogState>())
            })
                       .ToListAsync();

            pager.List = list;
            return(pager);
        }
Example #18
0
        public async Task <Results.BlogDetail> GetDetailAsync(bool readed = false)
        {
            DiagnosisNull(_blog);

            if (readed)
            {
                _blog.Views++;
                var author = _blog.Author;
                _blog.Author = null;

                await using var db = new LOPDbContext();
                db.Blogs.Update(_blog);
                int changeConut = await db.SaveChangesAsync();

                if (changeConut != 1)
                {
                    throw new Exception("增加已读人数出现错误");
                }
                _blog.Author = author;
            }

            int[]   targetIds   = _blog.TargetIds.SplitToInt(',').ToArray();
            Targets targets     = new Targets();
            var     targetNames = await targets.GetTargetsNameAsync(targetIds);

            Results.BlogDetail result = new Results.BlogDetail
            {
                Title         = _blog.Title,
                Targets       = targetNames,
                Content       = _blog.Content,
                Views         = _blog.Views,
                Likes         = _blog.Likes,
                Author        = _blog.Author.Name,
                AuthorAccount = _blog.Author.Account,
                DateTime      = _blog.CreateDate.ToString("yyyy/MM/dd HH:mm"),
                State         = KeyValue.Create(_blog.State, _blog.State.GetDescription <BlogState>())
            };
            return(result);
        }
Example #19
0
        /// <summary>
        /// 删除一个博文,只能删除自己的博文
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <(bool, string)> DeleteBlogAsync(int id, int clientId)
        {
            await using var db = new LOPDbContext();
            var blog = await db.Blogs.AsNoTracking().FirstOrDefaultAsync(blog => blog.Id == id);

            if (blog is null)
            {
                return(true, "");
            }
            if (blog.AuthorId != clientId)
            {
                return(false, "你没有权限删除这篇博文");
            }
            db.Blogs.Remove(blog);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount == 1)
            {
                return(true, "");
            }
            throw new Exception("删除博文失败");
        }
Example #20
0
        public virtual async Task <(bool, string)> ModifyUser(Models.ModifyUser model)
        {
            Validation validation = new Validation();

            if (!validation.ValidateUserName(model.Name))
            {
                return(false, $"用户名必须大于{NAME_MIN_LENGTH}位小于{NAME_MAX_LENGTH}位,却不能带有 {NAME_NOT_ALLOW_CHAR}");
            }
            if (!validation.ValidateEmail(model.Email))
            {
                return(false, "邮箱格式不正确");
            }

            await using var db = new LOPDbContext();
            DB.Tables.User user = await db.Users.AsNoTracking().FirstOrDefaultAsync(user => user.Id == Id);

            if (user is null)
            {
                return(false, "该用户不存在");
            }

            if (user.Name == model.Name && user.Email == model.Email)
            {
                return(true, "");
            }
            user.Name  = model.Name;
            user.Email = model.Email;
            db.Update(user);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount == 1)
            {
                UserCache.SetUserModel(user);
                Name = model.Name;
                return(true, "");
            }
            throw new Exception("修改失败");
        }
        /// <summary>
        /// 添加标签,返回标签 ID 列表
        /// </summary>
        /// <param name="newTargets"></param>
        /// <returns></returns>
        public static async Task <int[]> AppendTargetsAsync(string[] newTargets)
        {
            await using var db = new LOPDbContext();

            List <int> ids = new List <int>(newTargets.Length);

            foreach (string target in newTargets)
            {
                var model = await db.Targets.AsNoTracking().FirstOrDefaultAsync(t => t.Name.Equals(target, StringComparison.OrdinalIgnoreCase));

                if (model is null)
                {
                    model = new DB.Tables.Target
                    {
                        Name = target
                    };
                    db.Targets.Add(model);
                    await db.SaveChangesAsync();
                }
                ids.Add(model.Id);
            }
            return(ids.ToArray());
        }
Example #22
0
        public async Task <int> CreateBlogAsync(Models.NewPost model)
        {
            var targetIds = await Targets.AppendTargetsAsync(model.Targets);

            await using var db = new LOPDbContext();

            DB.Tables.Blog newBlog = new DB.Tables.Blog
            {
                Title      = model.Title,
                Content    = model.Content,
                TargetIds  = string.Join(',', targetIds),
                AuthorId   = model.AuthorId,
                State      = model.IsDraft ? (int)Blog.BlogState.Draft : (int)Blog.BlogState.Enabled,
                CreateDate = DateTime.Now
            };
            db.Blogs.Add(newBlog);
            int changeCount = await db.SaveChangesAsync();

            if (changeCount == 1)
            {
                return(newBlog.Id);
            }
            return(POST_DEFEATED);
        }
Example #23
0
        /// <summary>
        /// 禁用
        /// </summary>
        /// <returns></returns>
        public async Task <(bool, string)> DisableAsync()
        {
            if (_blog.State != (int)BlogState.Audit && _blog.State != (int)BlogState.Enabled)
            {
                return(false, $"只有{BlogState.Audit.GetDescription()}或{BlogState.Enabled.GetDescription()}的博文可以执行${BlogState.Disabled.GetDescription()}操作");
            }

            _blog.State = (int)BlogState.Disabled;
            var author = _blog.Author;

            _blog.Author = null;

            await using var db = new LOPDbContext();
            db.Blogs.Update(_blog);
            int changeConut = await db.SaveChangesAsync();

            if (changeConut != 1)
            {
                throw new Exception("禁用博文发生错误");
            }
            _blog.Author = author;

            return(true, "");
        }