Skip to content

Commit

Permalink
updated logic to get suggested tags for youtube videos
Browse files Browse the repository at this point in the history
  • Loading branch information
Oleksandr Holub committed Jan 13, 2024
1 parent ad12c1f commit 33df28c
Showing 1 changed file with 23 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using ShareLink.Application.Common.Abstraction;
using ShareLink.Application.Common.Dto;
using ShareLink.Application.Common.Services;
using ShareLink.Domain;
using ShareLink.Domain.Enums;

namespace ShareLink.Application.PreviewLinkHandler;

public class PreviewLinkHandler(IUrlParser urlParser, IGoogleApiService googleApiService)
public class PreviewLinkHandler(IUrlParser urlParser, IGoogleApiService googleApiService, IApplicationDbContext context)
: IRequestHandler<PreviewLinkRequest, PreviewLinkResponse>
{
public Task<PreviewLinkResponse> Handle(PreviewLinkRequest request, CancellationToken cancellationToken)
Expand All @@ -23,12 +25,7 @@ public Task<PreviewLinkResponse> Handle(PreviewLinkRequest request, Cancellation
private async Task<PreviewLinkResponse> HandleYoutube(string id)
{
var videoInfo = await googleApiService.GetYoutubeVideoInfo(id);
var tags = videoInfo.Tags
.Select(tag => tag.Trim().ToLower())
.Distinct()
.Where(x => x.Length is >= ValidationRules.Tag.MinTagLength and <= ValidationRules.Tag.MaxTagLength)
.Take(3)
.ToArray();
var tags = await FindMostMentionedTags(videoInfo.Tags);
var title = videoInfo.Title.Length > ValidationRules.LinkTitle.MaxLength
? videoInfo.Title[..(ValidationRules.LinkTitle.MaxLength - 3)] + "..."
: videoInfo.Title;
Expand All @@ -44,6 +41,25 @@ private async Task<PreviewLinkResponse> HandleYoutube(string id)
};
}

private async Task<string[]> FindMostMentionedTags(IEnumerable<string> youtubeVideoTags)
{
var allTags = await context.Tags.Select(tag => tag.Name).ToArrayAsync();
var tagOccurrences = new Dictionary<string, int>();

foreach (var videoTag in youtubeVideoTags.Distinct())
{
var lowerCaseVideoTag = videoTag.ToLowerInvariant();
var matchedTags = allTags.Where(tag => lowerCaseVideoTag.Contains(tag));
foreach (var matchedTag in matchedTags)
{
tagOccurrences.TryGetValue(matchedTag, out var value);
tagOccurrences[matchedTag] = ++value;
}
}

return tagOccurrences.OrderByDescending(kv => kv.Value).Take(ValidationRules.Tag.MaxTagsCount).Select(kv => kv.Key).ToArray();
}

private PreviewLinkResponse HandleUnknownSourceLink(string id) =>
new()
{
Expand Down

0 comments on commit 33df28c

Please sign in to comment.