Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Show topic tags as hashtag links in notification emails

Régis Hanol5977de153944
diff --git a/app/mailers/user_notifications.rb b/app/mailers/user_notifications.rb
index 2ef513b8abc..4af517e7cdb 100644
--- a/app/mailers/user_notifications.rb
+++ b/app/mailers/user_notifications.rb
@@ -789,6 +789,7 @@ class UserNotifications < ActionMailer::Base
add_re_to_subject: add_re_to_subject,
show_category_in_subject: show_category_in_subject,
show_tags_in_subject: show_tags_in_subject,
+ tag_names: tags,
private_reply: post.topic.private_message?,
subject_pm: subject_pm,
participants: participants,
diff --git a/app/services/hashtag_autocomplete_service.rb b/app/services/hashtag_autocomplete_service.rb
index 8be0458952c..82df3a57ff2 100644
--- a/app/services/hashtag_autocomplete_service.rb
+++ b/app/services/hashtag_autocomplete_service.rb
@@ -154,6 +154,25 @@ class HashtagAutocompleteService
@guardian = guardian
end
+ def hashtags_for(type, slugs)
+ return [] if slugs.blank?
+
+ higher_ranked_types =
+ HashtagAutocompleteService
+ .ordered_types_for_context("topic-composer")
+ .take_while { |candidate| candidate != type }
+
+ conflicting_refs =
+ higher_ranked_types
+ .flat_map { |candidate| lookup_for_type(candidate, guardian, slugs) }
+ .to_set { |item| UrlHelper.unencode(item.ref).downcase }
+
+ slugs.map do |slug|
+ ref = conflicting_refs.include?(slug.downcase) ? "#{slug}::#{type}" : slug
+ HashtagRewriter.usable_ref?(ref) ? "##{ref}" : slug
+ end
+ end
+
def find_by_ids(ids_by_type)
HashtagAutocompleteService
.data_source_types
diff --git a/docs/developer-guides/docs/03-code-internals/10-markdown-extensions.md b/docs/developer-guides/docs/03-code-internals/10-markdown-extensions.md
index 1761c840cf9..9d7c2dfd4ca 100644
--- a/docs/developer-guides/docs/03-code-internals/10-markdown-extensions.md
+++ b/docs/developer-guides/docs/03-code-internals/10-markdown-extensions.md
@@ -83,6 +83,19 @@ export function setup(helper) {
## Discourse specific extensions
+### Generating hashtag references in Ruby
+
+Use `HashtagAutocompleteService#hashtags_for` to build references for generated Markdown:
+
+```ruby
+HashtagAutocompleteService.new(user.guardian).hashtags_for("tag", ["bug", "support"]).join(" ")
+```
+
+If a visible category has the slug `bug`, the result is `#bug::tag #support`.
+Pass names already filtered for the viewer's visibility. Order and case are
+preserved, collisions are checked against higher-priority types, and a name the
+hashtag rule cannot match falls back to plain text.
+
### BBCode
Discourse contains 2 rulers you can use for custom BBCode tags. An inline and block level ruler.
diff --git a/lib/email/message_builder.rb b/lib/email/message_builder.rb
index 71180f2721d..4cc6d9b6fd3 100644
--- a/lib/email/message_builder.rb
+++ b/lib/email/message_builder.rb
@@ -216,7 +216,7 @@ module Email
optional_re: "",
optional_pm: "",
optional_cat: format_category,
- optional_tags: format_tags,
+ optional_tags: ->(_) { format_tag_hashtags },
)
body = I18n.t("#{@opts[:template]}.text_body_template", augmented_template_args).dup
@@ -404,5 +404,14 @@ module Email
""
end
end
+
+ def format_tag_hashtags
+ return "" if @opts[:tag_names].blank?
+ return format_tags if HashtagAutocompleteService.data_source_types.exclude?("tag")
+
+ guardian = @opts[:recipient_user]&.guardian || Guardian.new
+ hashtags = HashtagAutocompleteService.new(guardian).hashtags_for("tag", @opts[:tag_names])
+ "#{hashtags.join(" ")} "
+ end
end
end
diff --git a/lib/email/renderer.rb b/lib/email/renderer.rb
index d23531430a1..b268d8cb7d1 100644
--- a/lib/email/renderer.rb
+++ b/lib/email/renderer.rb
@@ -25,7 +25,7 @@ module Email
template: "layouts/email_template",
format: :html,
locals: {
- html_body: PrettyText.cook(text).html_safe,
+ html_body: PrettyText.cook(text, user_id: @opts[:user_id]).html_safe,
email_preview: email_preview,
},
)
diff --git a/lib/email/sender.rb b/lib/email/sender.rb
index 0202a5d1a89..92e2243ea97 100644
--- a/lib/email/sender.rb
+++ b/lib/email/sender.rb
@@ -69,9 +69,7 @@ module Email
@message.charset = "UTF-8"
- opts = {}
-
- renderer = Email::Renderer.new(@message, opts)
+ renderer = Email::Renderer.new(@message, user_id: @user&.id)
if @message.html_part
@message.html_part.body = renderer.html
diff --git a/spec/lib/email/message_builder_spec.rb b/spec/lib/email/message_builder_spec.rb
index af9a6659b7f..cc46595cf94 100644
--- a/spec/lib/email/message_builder_spec.rb
+++ b/spec/lib/email/message_builder_spec.rb
@@ -551,20 +551,31 @@ RSpec.describe Email::MessageBuilder do
let(:templated_builder) { Email::MessageBuilder.new(to_address, template: "mystery") }
let(:rendered_template) { "rendered template" }
- it "has the body rendered from a template" do
- I18n
- .expects(:t)
- .with(
- "mystery.text_body_template",
- templated_builder.template_args.merge(
- optional_re: "",
- optional_pm: "",
- optional_cat: "",
- optional_tags: "",
- ),
+ it "renders the body without querying for unused tags" do
+ template = "user_notifications.user_replied"
+ TranslationOverride.upsert!(I18n.locale, "#{template}.text_body_template", "%{message}")
+ builder = described_class.new(to_address, template:, message: body, tag_names: ["bug"])
+
+ expect(builder.body).to eq(body)
+
+ queries = track_sql_queries { builder.body }
+
+ expect(queries).to be_empty
+ end
+
+ it "renders plain tag names when tagging is disabled" do
+ SiteSetting.tagging_enabled = false
+ template = "user_notifications.user_replied"
+ TranslationOverride.upsert!(I18n.locale, "#{template}.text_body_template", "%{optional_tags}")
+ builder =
+ described_class.new(
+ to_address,
+ template:,
+ tag_names: %w[bug support],
+ show_tags_in_subject: "bug support",
)
- .returns(rendered_template)
- expect(templated_builder.body).to eq(rendered_template)
+
+ expect(builder.body).to eq("bug support ")
end
it "has the subject rendered from a template" do
diff --git a/spec/lib/email/sender_spec.rb b/spec/lib/email/sender_spec.rb
index ca349c240e5..d108b49360a 100644
--- a/spec/lib/email/sender_spec.rb
+++ b/spec/lib/email/sender_spec.rb
@@ -14,6 +14,24 @@ RSpec.describe Email::Sender do
message.stubs(:deliver!).returns(Net::SMTP::Response.new("250", mock_smtp_transaction_response))
end
+ it "renders recipient-visible tag hashtags as absolute links in HTML while retaining text hashtags" do
+ recipient = Fabricate(:admin)
+ tag = Fabricate(:tag)
+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [tag.name])
+ body = "Tags: ##{tag.name}::tag"
+
+ [[nil, []], [recipient, [tag.full_url]]].each do |user, expected_urls|
+ message = Mail::Message.new(to: recipient.email, body:)
+ stub_deliver_response(message)
+
+ Email::Sender.new(message, :user_replied, user).send
+
+ links = Nokogiri::HTML5.parse(message.html_part.body.decoded).css("a.hashtag-cooked")
+ expect(links.map { |link| link["href"] }).to eq(expected_urls)
+ expect(message.text_part.body.decoded).to eq(body)
+ end
+ end
+
context "when disable_emails is enabled" do
fab!(:user)
fab!(:moderator)
@@ -714,7 +732,7 @@ RSpec.describe Email::Sender do
> 3. If you graph these numbers, patterns emerge.
>
> Therefore: There are patterns everywhere in nature.
-
+
IMAGE #2
#{UploadMarkdown.new(@secure_image_2).image_markdown}
MD
@@ -727,7 +745,7 @@ RSpec.describe Email::Sender do
raw = <<~MD
IMAGE #3
#{UploadMarkdown.new(@secure_image_3).image_markdown}
-
+
ATTACHMENT
#{UploadMarkdown.new(@secure_attachment).attachment_markdown}
diff --git a/spec/mailers/user_notifications_spec.rb b/spec/mailers/user_notifications_spec.rb
index 26c6dc80439..a8b2eff57d7 100644
--- a/spec/mailers/user_notifications_spec.rb
+++ b/spec/mailers/user_notifications_spec.rb
@@ -705,7 +705,29 @@ RSpec.describe UserNotifications do
end
describe "optional placeholders in email body" do
- it "renders optional_tags, optional_cat, optional_pm, and optional_re in body templates" do
+ it "renders no body hashtags when the email tag limit is zero" do
+ SiteSetting.enable_max_tags_per_email_subject = true
+ SiteSetting.max_tags_per_email_subject = 0
+ TranslationOverride.upsert!(
+ I18n.locale,
+ "user_notifications.user_replied.text_body_template",
+ "Tags: %{optional_tags}\n\n",
+ )
+
+ mail =
+ UserNotifications.user_replied(
+ user,
+ post: response,
+ notification_type: notification.notification_type,
+ notification_data_hash: notification.data_hash,
+ )
+
+ expect(Email::Renderer.new(mail).text.lines.first.strip).to eq("Tags:")
+ end
+
+ it "renders optional placeholders with tag links in the body and plain tags in the subject" do
+ Fabricate(:category, name: tag2.name, slug: tag2.name.downcase)
+ SiteSetting.email_subject = "%{optional_tags}%{topic_title}"
custom_body = <<~BODY
You got a reply!
@@ -731,17 +753,19 @@ RSpec.describe UserNotifications do
notification_data_hash: notification.data_hash,
)
- body = mail.body.to_s
+ renderer = Email::Renderer.new(mail)
+ links = Nokogiri::HTML5.parse(renderer.html).css("a.hashtag-cooked")
- expect(body).to include(tag2.name)
- expect(body).to include(tag3.name)
- expect(body).to include(category.name)
-
- expect(body).not_to include("translation missing")
- expect(body).not_to include("%{optional_tags}")
- expect(body).not_to include("%{optional_cat}")
- expect(body).not_to include("%{optional_pm}")
- expect(body).not_to include("%{optional_re}")
+ expect(renderer.text).to include(
+ "Category: [#{category.name}]",
+ "Tags: ##{tag2.name}::tag ##{tag3.name} ##{tag1.name}",
+ "PM marker: \nRe marker: \n",
+ )
+ expect(renderer.text).not_to include(hidden_tag.name)
+ expect(links.map(&:text)).to eq([tag2, tag3, tag1].map { |tag| "##{tag.name}" })
+ expect(links.map { |link| link["href"] }).to eq([tag2, tag3, tag1].map(&:full_url))
+ expect(mail.subject).to eq("#{tag2.name} #{tag3.name} #{tag1.name} #{topic.title}")
+ expect(mail["X-Discourse-Tags"].value).to eq("#{tag2.name} #{tag3.name} #{tag1.name}")
end
end
diff --git a/spec/services/hashtag_autocomplete_service_spec.rb b/spec/services/hashtag_autocomplete_service_spec.rb
index 5153ec28f38..4d50aaf190d 100644
--- a/spec/services/hashtag_autocomplete_service_spec.rb
+++ b/spec/services/hashtag_autocomplete_service_spec.rb
@@ -56,6 +56,36 @@ RSpec.describe HashtagAutocompleteService do
end
end
+ describe "#hashtags_for" do
+ it "disambiguates visible collisions while preserving order and case" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+
+ expect(
+ service.hashtags_for("tag", [tag1.name, category1.slug.upcase, private_category.slug]),
+ ).to eq(["##{tag1.name}", "##{category1.slug.upcase}::tag", "##{private_category.slug}"])
+ end
+
+ it "disambiguates references beyond the autocomplete lookup limit" do
+ slugs = Array.new(described_class::HASHTAGS_PER_REQUEST + 1) { |index| "tag-#{index}" }
+ slugs << category1.slug
+
+ expect(service.hashtags_for("tag", slugs)).to eq(
+ slugs[0...-1].map { |slug| "##{slug}" } << "##{category1.slug}::tag",
+ )
+ end
+
+ it "disambiguates Unicode tags from encoded category slugs" do
+ SiteSetting.slug_generation_method = "encoded"
+ category = Fabricate(:category, name: "日本語")
+
+ expect(service.hashtags_for("tag", [category.name])).to eq(["##{category.name}::tag"])
+ end
+
+ it "falls back to the plain name when the reference cannot be matched" do
+ expect(service.hashtags_for("tag", ["l’amour"])).to eq(["l’amour"])
+ end
+ end
+
describe "#search" do
it "returns search results for tags and categories by default" do
expect(service.search("book", %w[category tag]).map(&:text)).to eq(