public bool CanSendCrowdactionEmail(Crowdaction crowdaction) => crowdaction.CanSendCrowdactionEmail(MaxNumberCrowdactionEmails, TimeEmailAllowedAfterCrowdactionEnd);
private async Task SeedRandomCrowdactions(IEnumerable <ApplicationUser> users, CancellationToken cancellationToken) { Random r = new Random(); DateTime now = DateTime.UtcNow; string?[] videoLinks = new[] { "https://www.youtube-nocookie.com/embed/aLzM_L5fjCQ", "https://www.youtube-nocookie.com/embed/Zvugem-tKyI", "https://www.youtube-nocookie.com/embed/xY0XTysJUDY", "https://www.youtube-nocookie.com/embed/2yfPLxQQG-k", null }; List <(Uri bannerImageUrl, Task <byte[]> bannerImageBytes)> bannerImages = new[] { "https://collaction-production.s3.eu-central-1.amazonaws.com/57136ed4-b7f6-4dd2-a822-9341e2e60d1e.png", "https://collaction-production.s3.eu-central-1.amazonaws.com/765bc57b-748e-4bb8-a27e-08db6b99ea3e.png", "https://collaction-production.s3.eu-central-1.amazonaws.com/e06bbc2d-02f7-4a9b-a744-6923d5b21f51.png", }.Select(b => new Uri(b)).Select(b => (b, DownloadFile(b, cancellationToken))).ToList(); List <(Uri descriptiveImageUrl, Task <byte[]> descriptiveImageBytes)> descriptiveImages = new[] { "https://collaction-production.s3.eu-central-1.amazonaws.com/107104bc-deeb-4f48-b3a5-f25585bebf89.png", "https://collaction-production.s3.eu-central-1.amazonaws.com/365f2dc9-1784-45ea-9cc7-d5f0ef1a480c.png", "https://collaction-production.s3.eu-central-1.amazonaws.com/6e6c12b1-eaae-4811-aa1c-c169d10f1a59.png", }.Select(b => new Uri(b)).Select(b => (b, DownloadFile(b, cancellationToken))).ToList(); await Task.WhenAll(descriptiveImages.Select(d => d.descriptiveImageBytes).Concat(bannerImages.Select(b => b.bannerImageBytes))).ConfigureAwait(false); List <string> tags = Enumerable.Range(0, seedOptions.NumberSeededTags) .Select(r => Faker.Internet.DomainWord()) .Distinct() .ToList(); var crowdactionNames = Enumerable.Range(0, seedOptions.NumberSeededCrowdactions) .Select(i => Faker.Company.Name()) .Distinct() .ToList(); List <string> userIds = await context.Users.Select(u => u.Id).ToListAsync(cancellationToken).ConfigureAwait(false); List <Crowdaction> crowdactions = new List <Crowdaction>(crowdactionNames.Count); // Generate random crowdactions foreach (string crowdactionName in crowdactionNames) { DateTime start = now.Date.AddDays(r.Next(-10, 20)); const int MaxTagsForCrowdaction = 4; IEnumerable <string> crowdactionTags = Enumerable.Range(0, r.Next(MaxTagsForCrowdaction + 1)) .Select(i => r.Next(tags.Count)) .Distinct() .Select(i => tags[i]) .ToList(); int numberCategories = Enum.GetValues(typeof(Category)).Length; List <Category> categories = new[] { (Category)r.Next(numberCategories), (Category)r.Next(numberCategories) }.Distinct().ToList(); (Uri descriptiveImageUrl, Task <byte[]> descriptiveImageBytes) = descriptiveImages[r.Next(descriptiveImages.Count)]; ImageFile?descriptiveImage = r.Next(3) == 0 ? null : await imageService.UploadImage(ToFormFile(descriptiveImageBytes.Result, descriptiveImageUrl), Faker.Company.BS(), MaxImageBannerDimensionPixels, cancellationToken).ConfigureAwait(false); (Uri bannerImageUrl, Task <byte[]> bannerImageBytes) = bannerImages[r.Next(bannerImages.Count)]; ImageFile?bannerImage = r.Next(3) == 0 ? null : await imageService.UploadImage(ToFormFile(bannerImageBytes.Result, bannerImageUrl), Faker.Company.BS(), MaxImageBannerDimensionPixels, cancellationToken).ConfigureAwait(false); ImageFile?cardImage = bannerImage == null ? null : await imageService.UploadImage(ToFormFile(bannerImageBytes.Result, bannerImageUrl), Faker.Company.BS(), MaxImageCardDimensionPixels, cancellationToken).ConfigureAwait(false); ApplicationUser owner = users.ElementAt(users.Count() - 1); int numberStatusses = Enum.GetValues(typeof(CrowdactionStatus)).Length; CrowdactionStatus status = (CrowdactionStatus)r.Next(numberStatusses); NewCrowdactionInternal newCrowdaction = new NewCrowdactionInternal( name: crowdactionName, description: $"<p>{string.Join("</p><p>", Faker.Lorem.Paragraphs(r.Next(3) + 1))}</p>", start: start, end: start.AddDays(r.Next(10, 40)).AddHours(23).AddMinutes(59).AddSeconds(59), categories: categories, tags: crowdactionTags, bannerImageFileId: bannerImage?.Id, descriptiveImageFileId: descriptiveImage?.Id, cardImageFileId: cardImage?.Id, creatorComments: r.Next(4) == 0 ? null : $"<p>{string.Join("</p><p>", Faker.Lorem.Paragraphs(r.Next(3) + 1))}</p>", goal: Faker.Company.CatchPhrase(), proposal: Faker.Company.BS(), target: r.Next(1, 10000), descriptionVideoLink: videoLinks.ElementAt(r.Next(videoLinks.Length)), displayPriority: (CrowdactionDisplayPriority)r.Next(3), status: (CrowdactionStatus)r.Next(3), ownerId: owner.Id, anonymousUserParticipants: r.Next(1, 8000)); Crowdaction crowdaction = await crowdactionService.CreateCrowdactionInternal(newCrowdaction, cancellationToken).ConfigureAwait(false); context.CrowdactionParticipants.AddRange( userIds.Where(userId => r.Next(2) == 0) .Select(userId => new CrowdactionParticipant(userId, crowdaction.Id, r.Next(2) == 1, now, Guid.NewGuid()))); await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); IEnumerable <CrowdactionComment> comments = Enumerable.Range(-24 * seedOptions.NumberDaysSeededForComments, 24 * seedOptions.NumberDaysSeededForComments) .Where(i => r.NextDouble() <= seedOptions.ProbabilityCommentSeededPerHour) .Select(i => { DateTime commentedAt = DateTime.Now.AddHours(i).AddMinutes(r.Next(-30, 30)).AddSeconds(r.Next(-30, 30)); string comment = $"<p>{string.Join("</p><p>", Faker.Lorem.Paragraphs(r.Next(2) + 1))}</p>"; string anonymousName = Faker.Name.First(); (string?userId, string?anonymousUser) = r.Next(3) == 0 ? ((string?)null, anonymousName.Substring(0, Math.Min(20, anonymousName.Length))) : (userIds[r.Next(userIds.Count)], null); var status = (CrowdactionCommentStatus)r.Next(3); return(new CrowdactionComment(comment, userId, anonymousUser, crowdaction.Id, commentedAt, status)); }); foreach (var comment in comments) // Insert one-by-one to preserve insertion order { context.CrowdactionComments.Add(comment); await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } } }
public async Task <CrowdactionResult> CreateCrowdaction(NewCrowdaction newCrowdaction, ClaimsPrincipal user, CancellationToken token) { logger.LogInformation("Validating new crowdaction"); IEnumerable <ValidationResult> validationResults = ValidationHelper.Validate(newCrowdaction, serviceProvider); if (validationResults.Any()) { return(new CrowdactionResult(validationResults)); } ApplicationUser?owner = await userManager.GetUserAsync(user).ConfigureAwait(false); if (owner == null) { return(new CrowdactionResult(new ValidationResult("Crowdaction owner could not be found"))); } if (await context.Crowdactions.AnyAsync(c => c.Name == newCrowdaction.Name, token).ConfigureAwait(false)) { return(new CrowdactionResult(new ValidationResult("A crowdaction with this name already exists", new[] { nameof(Crowdaction.Name) }))); } logger.LogInformation("Creating crowdaction: {0}", newCrowdaction.Name); var tagMap = new Dictionary <string, int>(); List <string> tags = newCrowdaction.Tags.Distinct().ToList(); if (tags.Any()) { var missingTags = tags.Except( await context.Tags .Where(t => tags.Contains(t.Name)) .Select(t => t.Name) .ToListAsync(token).ConfigureAwait(false)) .Select(t => new Tag(t)); if (missingTags.Any()) { context.Tags.AddRange(missingTags); await context.SaveChangesAsync(token).ConfigureAwait(false); } tagMap = await context.Tags .Where(t => tags.Contains(t.Name)) .ToDictionaryAsync(t => t.Name, t => t.Id, token).ConfigureAwait(false); } List <CrowdactionTag> crowdactionTags = tags.Select(t => new CrowdactionTag(tagId: tagMap[t])) .ToList(); var crowdaction = new Crowdaction( name: newCrowdaction.Name, status: CrowdactionStatus.Hidden, ownerId: owner.Id, target: newCrowdaction.Target, start: newCrowdaction.Start, end: newCrowdaction.End.Date.AddHours(23).AddMinutes(59).AddSeconds(59), description: newCrowdaction.Description, goal: newCrowdaction.Goal, proposal: newCrowdaction.Proposal, creatorComments: newCrowdaction.CreatorComments, descriptionVideoLink: newCrowdaction.DescriptionVideoLink?.Replace("www.youtube.com", "www.youtube-nocookie.com", StringComparison.Ordinal), displayPriority: CrowdactionDisplayPriority.Medium, bannerImageFileId: newCrowdaction.BannerImageFileId, cardImageFileId: newCrowdaction.CardImageFileId, descriptiveImageFileId: newCrowdaction.DescriptiveImageFileId, categories: newCrowdaction.Categories.Select(c => new CrowdactionCategory((c))).ToList(), tags: crowdactionTags); context.Crowdactions.Add(crowdaction); await context.SaveChangesAsync(token).ConfigureAwait(false); await RefreshParticipantCount(token).ConfigureAwait(false); await emailSender.SendEmailTemplated(owner.Email, $"Thank you for submitting \"{crowdaction.Name}\" on CollAction", "CrowdactionConfirmation").ConfigureAwait(false); IList <ApplicationUser> administrators = await userManager.GetUsersInRoleAsync(AuthorizationConstants.AdminRole).ConfigureAwait(false); await emailSender.SendEmailsTemplated(administrators.Select(a => a.Email), $"A new crowdaction was submitted on CollAction: \"{crowdaction.Name}\"", "CrowdactionAddedAdmin", crowdaction.Name).ConfigureAwait(false); logger.LogInformation("Created crowdaction: {0}", newCrowdaction.Name); return(new CrowdactionResult(crowdaction)); }
public CrowdactionResult(Crowdaction crowdaction) { Crowdaction = crowdaction; Succeeded = true; }