Exemple #1
0
        public async Task <SimilarPromptViewModel> Handle(SimilarPromptQuery request,
                                                          CancellationToken cancellationToken = default)
        {
            var query = _dbContext
                        .Prompts
                        .Where(prompt => !prompt.IsDraft)
                        .Where(prompt =>
                               EF.Functions.ILike(prompt.Title, NpgsqlHelper.SafeIlike(request.Title), NpgsqlHelper.EscapeChar));

            if (request.CurrentId.HasValue)
            {
                query = query.Where(e => e.Id != request.CurrentId.Value);
            }

            List <SimilarPromptDetailsViewModel>?similarPrompts = await query
                                                                  .AsNoTracking()
                                                                  .Select(prompt => new SimilarPromptDetailsViewModel {
                Id = prompt.Id, Title = prompt.Title
            })
                                                                  .ToListAsync(cancellationToken);

            if (similarPrompts.Count < 1)
            {
                return(new SimilarPromptViewModel {
                    Matched = false
                });
            }

            return(new SimilarPromptViewModel {
                Matched = true, SimilarPrompts = similarPrompts
            });
        }
        public async Task <GetUserViewModel> Handle(LogInQuery request, CancellationToken cancellationToken = default)
        {
            var  username = NpgsqlHelper.SafeIlike(request.Username);
            User?user     = await _dbContext
                            .Users
                            .AsNoTracking()
                            .FirstOrDefaultAsync(e => EF.Functions.ILike(e.Username, username, NpgsqlHelper.EscapeChar));

            if (user == null ||
                user.Password == null ||
                !BCrypt.Net.BCrypt.EnhancedVerify(request.Password, user.Password))
            {
                throw new LoginFailedException();
            }

            return(new GetUserViewModel {
                Id = user.Id, Username = user.Username, Role = user.Role
            });
        }
        public async Task <Unit> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            User?user = await _dbContext.Users.FindAsync(request.Id);

            if (user == null)
            {
                throw new UpdateUserNotFoundException();
            }

            if (!string.IsNullOrWhiteSpace(request.Username))
            {
                if (await _dbContext
                    .Users
                    .FirstOrDefaultAsync(e =>
                                         EF.Functions.ILike(e.Username, NpgsqlHelper.SafeIlike(request.Username),
                                                            NpgsqlHelper.EscapeChar) &&
                                         e.Id != request.Id) != null)
                {
                    throw new UsernameNotUniqueException();
                }

                user.Username = request.Username;
            }

            if (!string.IsNullOrWhiteSpace(request.Password))
            {
                user.Password = BCrypt.Net.BCrypt.EnhancedHashPassword(request.Password);
            }

            user.DateEdited = DateTime.UtcNow;

            _dbContext.Users.Update(user);
            await _dbContext.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
        public async Task <int> Handle(CreatePromptCommand request, CancellationToken cancellationToken = default)
        {
            if (request.ParentId.HasValue)
            {
                if (!_currentUserService.TryGetCurrentUser(out GetUserViewModel? user))
                {
                    throw new CreatePromptUnauthorizedParentException();
                }

                Prompt?parent = await _dbContext.Prompts.FindAsync(request.ParentId);

                if (parent.OwnerId != user !.Id)
                {
                    throw new CreatePromptUnauthorizedParentException();
                }
            }

            var isDraft = !request.ParentId.HasValue && request.SaveDraft;

            var prompt = new Prompt
            {
                AuthorsNote     = request.AuthorsNote?.Replace("\r\n", "\n"),
                DateCreated     = DateTime.UtcNow,
                DateEdited      = null,
                Memory          = request.Memory?.Replace("\r\n", "\n"),
                Nsfw            = request.Nsfw,
                PromptContent   = request.PromptContent.Replace("\r\n", "\n"),
                Quests          = request.Quests?.Replace("\r\n", "\n"),
                Title           = request.Title.Replace("\r\n", "\n"),
                Description     = request.Description?.Replace("\r\n", "\n"),
                OwnerId         = request.OwnerId,
                Upvote          = 0,
                Views           = 0,
                IsDraft         = isDraft,
                PublishDate     = isDraft ? null : (DateTime?)DateTime.UtcNow,
                ParentId        = request.ParentId,
                ScriptZip       = request.ScriptZip,
                NovelAiScenario = string.IsNullOrWhiteSpace(request.NovelAiScenario) ? null : request.NovelAiScenario,
                HoloAiScenario  = string.IsNullOrWhiteSpace(request.HoloAiScenario) ? null :  request.HoloAiScenario
            };

            foreach (var worldInfo in request.WorldInfos)
            {
                if (string.IsNullOrWhiteSpace(worldInfo.Entry) || string.IsNullOrWhiteSpace(worldInfo.Keys))
                {
                    continue;
                }

                prompt.WorldInfos.Add(new WorldInfo
                {
                    DateCreated = DateTime.UtcNow,
                    Entry       = worldInfo.Entry.Replace("\r\n", "\n"),
                    Keys        = worldInfo.Keys.Replace("\r\n", "\n"),
                    Prompt      = prompt
                });
            }

            var promptTags = request.PromptTags.Split(',').Select(p => p.Trim().ToLower()).Distinct();

            foreach (var promptTag in promptTags)
            {
                if (string.IsNullOrWhiteSpace(promptTag))
                {
                    continue;
                }

                if (string.Equals(promptTag, "nsfw", StringComparison.OrdinalIgnoreCase))
                {
                    prompt.Nsfw = true;
                    continue;
                }

                Tag?tag = await _dbContext.Tags.FirstOrDefaultAsync(e =>
                                                                    EF.Functions.ILike(e.Name, NpgsqlHelper.SafeIlike(promptTag), NpgsqlHelper.EscapeChar), cancellationToken : cancellationToken);

                if (tag == null)
                {
                    prompt.PromptTags.Add(new PromptTag {
                        Prompt = prompt, Tag = new Tag {
                            Name = promptTag
                        }
                    });
                }
                else
                {
                    prompt.PromptTags.Add(new PromptTag {
                        Prompt = prompt, Tag = tag
                    });
                }
            }

            _dbContext.Prompts.Add(prompt);
            await _dbContext.SaveChangesAsync(cancellationToken);

            return(prompt.Id);
        }
        public async Task <Unit> Handle(UpdatePromptCommand request, CancellationToken cancellationToken = default)
        {
            if (!_currentUserService.TryGetCurrentUser(out GetUserViewModel? user))
            {
                return(Unit.Value);
            }

            Prompt?prompt = await _dbContext.Prompts
                            .Include(e => e.PromptTags)
                            .Include(e => e.WorldInfos)
                            .FirstOrDefaultAsync(e => e.Id == request.Id, cancellationToken);

            var isOwner      = user !.Id == prompt.OwnerId;
            var canEditField = isOwner ? isOwner : (user.Role & RoleEnum.FieldEdit) != 0;
            var canEditTags  = isOwner ? isOwner : (user.Role & RoleEnum.TagEdit) != 0;

            if (canEditField)
            {
                var isDraft = !prompt.ParentId.HasValue &&
                              (isOwner
                                                      ? request.SaveDraft
                                                      : prompt.IsDraft);
                prompt.AuthorsNote   = request.AuthorsNote?.Replace("\r\n", "\n");
                prompt.DateEdited    = DateTime.UtcNow;
                prompt.Memory        = request.Memory?.Replace("\r\n", "\n");
                prompt.Nsfw          = request.Nsfw;
                prompt.PromptContent = request.PromptContent.Replace("\r\n", "\n");
                prompt.Quests        = request.Quests?.Replace("\r\n", "\n");
                prompt.Title         = request.Title.Replace("\r\n", "\n");
                prompt.Description   = request.Description?.Replace("\r\n", "\n");
                prompt.WorldInfos    = new List <WorldInfo>();
                prompt.IsDraft       = isDraft;
                prompt.PublishDate ??= isDraft ? null : (DateTime?)DateTime.UtcNow;
                prompt.ScriptZip = isOwner
                                        ? request.ScriptZip ?? prompt.ScriptZip
                                        : prompt.ScriptZip;
                prompt.NovelAiScenario = string.IsNullOrWhiteSpace(request.NovelAiScenario) ? null : request.NovelAiScenario;
                prompt.HoloAiScenario  = string.IsNullOrWhiteSpace(request.HoloAiScenario) ? null :  request.HoloAiScenario;

                foreach (var worldInfo in request.WorldInfos)
                {
                    if (string.IsNullOrWhiteSpace(worldInfo.Entry) || string.IsNullOrWhiteSpace(worldInfo.Keys))
                    {
                        continue;
                    }

                    prompt.WorldInfos.Add(new WorldInfo
                    {
                        DateCreated = DateTime.UtcNow,
                        Entry       = worldInfo.Entry.Replace("\r\n", "\n"),
                        Keys        = worldInfo.Keys.Replace("\r\n", "\n"),
                        Prompt      = prompt
                    });
                }
            }

            if (canEditTags)
            {
                prompt.PromptTags = new List <PromptTag>();
                var promptTags =
                    request.PromptTags.Split(',').Select(p => p.Trim().ToLower()).Distinct();
                foreach (var promptTag in promptTags)
                {
                    if (string.IsNullOrWhiteSpace(promptTag))
                    {
                        continue;
                    }

                    if (string.Equals(promptTag, "nsfw", StringComparison.OrdinalIgnoreCase))
                    {
                        prompt.Nsfw = true;
                        continue;
                    }

                    Tag?tag = await _dbContext.Tags.FirstOrDefaultAsync(e =>
                                                                        EF.Functions.ILike(e.Name, NpgsqlHelper.SafeIlike(promptTag), NpgsqlHelper.EscapeChar));

                    if (tag == null)
                    {
                        prompt.PromptTags.Add(new PromptTag {
                            Prompt = prompt, Tag = new Tag {
                                Name = promptTag
                            }
                        });
                    }
                    else
                    {
                        prompt.PromptTags.Add(new PromptTag {
                            Prompt = prompt, Tag = tag
                        });
                    }
                }
            }

            _dbContext.Prompts.Update(prompt);
            await _dbContext.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }