max ray
max ray

Reputation: 25

How to set URL preview for specific urls in Tinymce editor integrated to ASP.NET Core 6 MVC

I'm using TinyMCE editor in my ASP.NET Core 6 MVC project. I added a function that replace links to its preview section and it worked well.

But it replaced all the urls to the preview including the contents section.

I need to leave some urls like them as general url link, and want to change urls I select.

Here's my current code:

private async Task<string> ReplaceUrlsWithPreviews(string content)
{
    var anchorRegex = new Regex(@"<a[^>]*href=[""'](?<url>[^""']+)[""'][^>]*>(?<text>.*?)<\/a>", RegexOptions.IgnoreCase);

    // Find all anchor tags
    var matches = anchorRegex.Matches(content);

    foreach (Match match in matches)
    {
        var url = match.Groups["url"].Value;
        var linkText = match.Groups["text"].Value;

        // Fetch metadata for the URL
        var preview = await FetchMetadataFromUrl(url);

        // If metadata is found, generate preview HTML
        if (preview != null)
        {
            var previewHtml = GeneratePreviewHTML(preview);

            // Replace the entire <a> tag with the generated preview HTML
            content = content.Replace(match.Value, previewHtml);
        }
    }

    return content;
}

public static bool isValidUrl(string url)
{
    string pattern = @"^[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
    Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    var isMatch = !reg.IsMatch(url);
    return isMatch;
}

// Fetch metadata (OpenGraph/TwitterCard) for URL
private async Task<LinkPreview> FetchMetadataFromUrl(string url)
{
    var httpClient = new HttpClient();
    var response = await httpClient.GetStringAsync(url);
    var doc = new HtmlDocument();
    doc.LoadHtml(response);

    var preview = new LinkPreview
    {
        Title = GetMetaTagContent(doc, "og:title") ?? GetTitleTag(doc),
        Description = GetMetaTagContent(doc, "og:description")??"",
        Image = GetMetaTagContent(doc, "og:image") ?? "/img/preview.png",
        Url = url
    };

    return preview;
}

private string? GetMetaTagContent(HtmlDocument doc, string property)
{
    return doc.DocumentNode.SelectSingleNode($"//meta[@property='{property}']")?.GetAttributeValue("content", null);
}

private string GetTitleTag(HtmlDocument doc)
{
    return doc.DocumentNode.SelectSingleNode("//title")?.InnerText??"";
}

// Generate HTML for link preview
private string GeneratePreviewHTML(LinkPreview preview)
{
    return $@"
        <a class=""link-preview"" data-url=""{preview.Url}"" href=""{preview.Url}"" target=""_blank"" style=""text-decoration: none; color: inherit;width:100%;display:flex"">
            <div style=""border: 1px solid #ddd; padding: 10px; border-radius: 5px; display: flex; align-items: center;"">
                <img src=""{preview.Image}"" alt=""Preview Image"" style=""width: 220px; height: 150px; object-fit: cover; margin-right: 10px;"" />
                <div class=""link-details"" style=""flex-grow: 1;word-break:break-word"">
                    <h4 style=""margin: 0 0 10px;"">{preview.Title}</h4>
                    <p style=""margin: 0; color: #555;"">{preview.Description}</p>
                </div>
            </div>
        </a>";
}

How can I change this function for my purpose in TinyMCE editor?

I'm looking for your kind advice.

Thanks in advance.

Upvotes: 0

Views: 34

Answers (0)

Related Questions