A platform for community discussion. Free, open, simple.
FIX: Include full event details in notification emails (#40880)
Régis Hanolc1d21a12635e
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/email_renderer.rb b/plugins/discourse-calendar/lib/discourse_post_event/email_renderer.rbnew file mode 100644index 00000000000..79616b863be--- /dev/null+++ b/plugins/discourse-calendar/lib/discourse_post_event/email_renderer.rb@@ -0,0 +1,217 @@+# frozen_string_literal: true++module DiscoursePostEvent+ class EmailRenderer+ RECURRENCE_ORDINALS = %w[first second third fourth]++ def self.render(event_node, post)+ new(event_node, post).to_html+ end++ def initialize(event_node, post)+ @event_node = event_node+ @post = post+ @event = DiscoursePostEvent::Event.includes(:image_upload, :event_dates).find_by(id: post.id)+ @starts_at = event_node["data-start"]+ @timezone = event_node["data-timezone"] || "UTC"+ @all_day = event_node["data-all-day"] == "true"+ end++ def to_html+ rows = [+ image_row,+ name_row,+ status_and_creator_row,+ dates_row,+ recurrence_row,+ location_row,+ url_row,+ invitees_row,+ description_row,+ ].join++ <<~HTML+ <table cellspacing="0" cellpadding="0" border="0" style="border: 1px solid #dedede; margin-bottom: 10px; width: 100%;">+ #{rows}+ </table>+ HTML+ end++ private++ attr_reader :event_node, :post, :starts_at, :timezone++ def image_row+ return "" if @event&.image_upload_id.blank?++ image_url = UrlHelper.absolute(@event.image_upload.url)+ <<~HTML+ <tr>+ <td style="padding: 0;">+ <img src="#{CGI.escape_html(image_url)}" style="width: 100%; max-height: 400px; object-fit: cover; display: block;" />+ </td>+ </tr>+ HTML+ end++ def name_row+ name = event_node["data-name"] || post.topic.title+ name = CGI.escape_html(Emoji.gsub_emoji_to_unicode(name))+ <<~HTML+ <tr>+ <td style="padding: 12px;">+ <a href="#{post.full_url}" style="font-weight: bold; font-size: 1.1em;">#{name}</a>+ </td>+ </tr>+ HTML+ end++ def muted_row(content)+ return "" if content.blank?++ <<~HTML+ <tr>+ <td style="padding: 0 12px 12px; color: #666;">#{content}</td>+ </tr>+ HTML+ end++ def status_and_creator_row+ muted_row([status_label, creator_label].compact.join(" · "))+ end++ def dates_row+ muted_row(CGI.escape_html(dates))+ end++ def recurrence_row+ label = recurrence_label+ muted_row(label && CGI.escape_html(label))+ end++ def location_row+ location = event_node["data-location"]+ return "" if location.blank?++ muted_row(PrettyText.cook(location))+ end++ def url_row+ url = event_node["data-url"].to_s.strip+ return "" if url.blank?++ href = web_url?(url) ? url : "https://#{url}"+ <<~HTML+ <tr>+ <td style="padding: 0 12px 12px;"><a href="#{CGI.escape_html(href)}">#{CGI.escape_html(url)}</a></td>+ </tr>+ HTML+ end++ def web_url?(url)+ url.match?(%r{\A(?:https?://|mailto:)}i)+ end++ def invitees_row+ return "" if @event.nil? || @event.standalone? || @event.minimal++ muted_row(+ CGI.escape_html(card_t("models.invitee.status.going_count", count: @event.going_count)),+ )+ end++ def description_row+ return "" if @event&.description.blank?++ muted_row(DiscoursePostEvent::EventParser.linkify_description(@event.description, post:))+ end++ def dates+ return "-" if @event&.expired? && @event.recurring?++ suffix = timezone_suffix+ formatted = "#{format_date(starts_at)}#{suffix}"++ ends_at = event_node["data-end"]+ formatted = "#{formatted} → #{format_date(ends_at)}#{suffix}" if ends_at++ formatted+ end++ def format_date(value)+ format = all_day? ? "%B %-d, %Y" : "%B %-d, %Y %-I:%M %p"+ DateTime.parse(value).strftime(format)+ rescue StandardError+ value+ end++ def timezone_suffix+ all_day? ? "" : " (#{timezone})"+ end++ def status_label+ return nil if @event.nil?+ return card_t("models.event.expired") if @event.expired?+ return card_t("models.event.closed") if @event.closed++ key =+ if @event.standalone?+ "standalone"+ elsif @event.private?+ "private"+ else+ "public"+ end+ card_t("models.event.status.#{key}.title")+ end++ def creator_label+ user = post.user+ return nil if user.nil?++ name = SiteSetting.enable_names? ? user.display_name : user.username+ "#{card_t("created_by")} #{CGI.escape_html(name)}"+ end++ def recurrence_label+ recurrence = @event&.recurrence+ return nil if recurrence.blank? || EventValidator::VALID_RECURRENCES.exclude?(recurrence)++ card_t("builder_modal.recurrence.#{recurrence}", **recurrence_context)+ rescue StandardError+ nil+ end++ def recurrence_context+ ref = recurrence_ref+ return {} if ref.nil?++ { weekday: ref.strftime("%A"), ordinal: recurrence_ordinal(ref) }+ end++ def recurrence_ref+ return Date.parse(starts_at) if all_day?++ zone = ActiveSupport::TimeZone[timezone] || ActiveSupport::TimeZone["UTC"]+ zone.parse(starts_at)+ rescue StandardError+ nil+ end++ def recurrence_ordinal(ref)+ day_of_month = ref.mday+ days_in_month = Date.new(ref.year, ref.month, -1).day+ is_last = day_of_month + 7 > days_in_month+ key = is_last ? "last" : RECURRENCE_ORDINALS[(day_of_month / 7.0).ceil - 1]+ card_t("builder_modal.recurrence.ordinals.#{key}")+ end++ def card_t(key, **options)+ I18n.t("js.discourse_post_event.#{key}", **options)+ end++ def all_day?+ @all_day+ end+ end+enddiff --git a/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rb b/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rbindex 83879c93469..ebc9564c4ea 100644--- a/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rb+++ b/plugins/discourse-calendar/lib/discourse_post_event/event_parser.rb@@ -2,6 +2,8 @@module DiscoursePostEventclass EventParser+ HTTP_URL_REGEXP = URI::DEFAULT_PARSER.make_regexp(%w[http https])+VALID_OPTIONS = [:start,:end,@@ -80,13 +82,19 @@ module DiscoursePostEventenddef self.linkify_description(text, post: nil)- escaped = ERB::Util.html_escape(text)- html =- escaped- .gsub(URI::DEFAULT_PARSER.make_regexp(%w[http https])) do |url|- "<a href=\"#{url}\">#{url}</a>"- end- .gsub(/\r\n?|\n/, "<br>")+ text = text.to_s++ html = +""+ cursor = 0+ text.scan(HTTP_URL_REGEXP) do+ match = Regexp.last_match+ html << ERB::Util.html_escape(text[cursor...match.begin(0)])+ escaped_url = ERB::Util.html_escape(match[0])+ html << "<a href=\"#{escaped_url}\">#{escaped_url}</a>"+ cursor = match.end(0)+ end+ html << ERB::Util.html_escape(text[cursor..])+ html.gsub!(/\r\n?|\n/, "<br>")doc = Nokogiri::HTML5.fragment(html)add_nofollow = post.nil? || post.add_nofollow?diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rbindex 6454306d49c..b3030983c29 100644--- a/plugins/discourse-calendar/plugin.rb+++ b/plugins/discourse-calendar/plugin.rb@@ -175,6 +175,7 @@ after_initialize dorequire_relative "jobs/regular/discourse_post_event/bump_topic"require_relative "jobs/regular/discourse_post_event/send_reminder"require_relative "jobs/regular/discourse_post_event/warm_livestream_onebox"+ require_relative "lib/discourse_post_event/email_renderer"require_relative "lib/discourse_post_event/engine"require_relative "lib/discourse_post_event/event_finder"require_relative "lib/discourse_post_event/event_parser"@@ -649,73 +650,12 @@ after_initialize dofragment.css(".discourse-post-event").each do |event_node|- tz = event_node["data-timezone"] || "UTC"- starts_at = event_node["data-start"]- ends_at = event_node["data-end"]-- formatted_start =- begin- DateTime.parse(starts_at).strftime("%B %-d, %Y %-I:%M %p")- rescue StandardError- starts_at- end- dates = "#{formatted_start} (#{tz})"-- if ends_at- formatted_end =- begin- DateTime.parse(ends_at).strftime("%B %-d, %Y %-I:%M %p")- rescue StandardError- ends_at- end- dates = "#{dates} → #{formatted_end} (#{tz})"- end-- event_name = event_node["data-name"] || post.topic.title- location = event_node["data-location"]- url = event_node["data-url"]-- event = DiscoursePostEvent::Event.includes(:image_upload).find_by(id: post.id)- image_url = UrlHelper.absolute(event.image_upload.url) if event&.image_upload_id-- rows = +""-- rows << <<~HTML if image_url.present?- <tr>- <td style="padding: 0;">- <img src="#{CGI.escape_html(image_url)}" style="width: 100%; max-height: 400px; object-fit: cover; display: block;" />- </td>- </tr>- HTML-- rows << <<~HTML- <tr>- <td style="padding: 12px;">- <a href="#{Discourse.base_url}#{post.url}" style="font-weight: bold; font-size: 1.1em;">#{CGI.escape_html(event_name)}</a>- </td>- </tr>- <tr>- <td style="padding: 0 12px 12px; color: #666;">#{CGI.escape_html(dates)}</td>- </tr>- HTML-- rows << <<~HTML if location.present?- <tr>- <td style="padding: 0 12px 12px; color: #666;">#{CGI.escape_html(location)}</td>- </tr>- HTML-- rows << <<~HTML if url.present?- <tr>- <td style="padding: 0 12px 12px;"><a href="#{CGI.escape_html(url)}">#{CGI.escape_html(url)}</a></td>- </tr>- HTML-- event_node.replace <<~HTML- <table cellspacing="0" cellpadding="0" border="0" style="border: 1px solid #dedede; margin-bottom: 10px; width: 100%;">- #{rows}- </table>- HTML+ event_node.replace(DiscoursePostEvent::EmailRenderer.render(event_node, post))+ rescue => e+ Discourse.warn_exception(+ e,+ message: "Failed to render event in email for post #{post&.id}",+ )endendenddiff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rbindex dc696d3f552..447b215e2dd 100644--- a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb@@ -165,6 +165,15 @@ describe DiscoursePostEvent::EventParser do'See <a href="https://example.com">https://example.com</a>',)end++ it "does not leak markup out of the generated href when a url is followed by html" do+ result = parser.linkify_description('http://example.com/"><script>alert(1)</script>')++ doc = Nokogiri::HTML5.fragment(result)+ expect(doc.css("script")).to be_empty+ expect(doc.at_css("a")["href"]).to eq("http://example.com/")+ expect(result).not_to include("<script>")+ endendcontext "with custom fields" dodiff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rbindex 42f93cb3dfb..cfc5c9706f9 100644--- a/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rb+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/pretty_text_spec.rb@@ -10,7 +10,7 @@ describe PrettyText docontext "with a public event" dodescribe "An event is displayed in an email" do- fab!(:user_1, :user) { Fabricate(:user, admin: true) }+ fab!(:user_1, :user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }context "when the event has no name" dolet(:post_1) { create_post_with_event(user_1) }@@ -45,6 +45,16 @@ describe PrettyText doexpect(result).to include("Pancakes event <a>with html chars</a>")end++ it "renders emoji in the name (matching the on-site card)" do+ post = create_post_with_event(user_1, 'name="Launch :rocket:"')++ cooked = PrettyText.cook(post.raw)+ result = PrettyText.format_for_email(cooked, post)++ expect(result).to include("🚀")+ expect(result).not_to include(":rocket:")+ endendcontext "when the event has an end date" do@@ -74,6 +84,7 @@ describe PrettyText docontext "when the event has a location" dolet(:post_1) { create_post_with_event(user_1, 'location="Conference Room A"') }+ let(:post_2) { create_post_with_event(user_1, 'location="https://maps.example.com"') }it "displays the location" docooked = PrettyText.cook(post_1.raw)@@ -81,10 +92,18 @@ describe PrettyText doexpect(result).to include("Conference Room A")end++ it "cooks links in the location (matching the on-site card)" do+ cooked = PrettyText.cook(post_2.raw)+ result = PrettyText.format_for_email(cooked, post_2)++ expect(result).to include('href="https://maps.example.com"')+ endendcontext "when the event has a url" dolet(:post_1) { create_post_with_event(user_1, 'url="https://example.com/meeting"') }+ let(:post_2) { create_post_with_event(user_1, 'url="example.com"') }it "displays the url" docooked = PrettyText.cook(post_1.raw)@@ -93,6 +112,22 @@ describe PrettyText doexpect(result).to include('href="https://example.com/meeting"')expect(result).to include("https://example.com/meeting")end++ it "prepends a scheme to a scheme-less url so the link is absolute" do+ cooked = PrettyText.cook(post_2.raw)+ result = PrettyText.format_for_email(cooked, post_2)++ expect(result).to include('href="https://example.com"')+ expect(result).to include(">example.com</a>")+ end++ it "makes a url with a non-web scheme absolute" do+ post_3 = create_post_with_event(user_1, 'url="ftp://files.example.com"')+ cooked = PrettyText.cook(post_3.raw)+ result = PrettyText.format_for_email(cooked, post_3)++ expect(result).to include('href="https://ftp://files.example.com"')+ endendcontext "when the event has an image" do@@ -107,6 +142,175 @@ describe PrettyText doexpect(result).to include(upload.url)endend++ context "when the event has a description" do+ let(:post_1) do+ start = (Time.now - 10.seconds).utc.iso8601(3)+ PostCreator.create!(+ user_1,+ title: "Sell a boat party ##{SecureRandom.alphanumeric}",+ raw:+ "[event start=\"#{start}\"]\nJoin us at https://example.com\nfor pancakes\n[/event]",+ ).reload+ end++ it "displays the description with links and line breaks" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("Join us at")+ expect(result).to include('href="https://example.com"')+ expect(result).to include("<br")+ expect(result).to include("for pancakes")+ end++ it "escapes html in the description" do+ post_1.event.update!(description: "Tom & Jerry <script>alert(1)</script>")++ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("Tom & Jerry <script>")+ expect(result).not_to include("<script>")+ end+ end++ context "when the event is all-day" do+ let(:post_1) do+ PostCreator.create!(+ user_1,+ title: "Sell a boat party ##{SecureRandom.alphanumeric}",+ raw: "[event start=\"2018-06-05\" all-day=\"true\"]\n[/event]",+ ).reload+ end++ it "displays the date without a time or timezone" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("June 5, 2018")+ expect(result).not_to include("12:00 AM")+ expect(result).not_to include("(UTC)")+ end+ end++ context "when the event recurs" do+ let(:post_1) { create_post_with_event(user_1, 'recurrence="every_week"') }+ let(:post_2) { create_post_with_event(user_1, 'recurrence="every_month"') }++ it "displays the weekly recurrence" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("Every Tuesday")+ end++ it "displays the monthly recurrence with its ordinal" do+ cooked = PrettyText.cook(post_2.raw)+ result = PrettyText.format_for_email(cooked, post_2)++ expect(result).to include("The first Tuesday of every month")+ end+ end++ context "when the event is closed" do+ let(:post_1) { create_post_with_event(user_1, 'status="public" closed="true"') }++ it "displays the closed status" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("Closed")+ end+ end++ context "with the event creator" do+ let(:post_1) { create_post_with_event(user_1) }++ it "displays who created the event" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("Created by")+ expect(result).to include(user_1.display_name)+ end++ it "shows the username instead of the name when names are disabled" do+ SiteSetting.enable_names = false+ user_1.update!(name: "Top Secret Name")++ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include(user_1.username)+ expect(result).not_to include("Top Secret Name")+ end+ end++ context "when the event has attendees" do+ let(:post_1) { create_post_with_event(user_1, 'status="public"') }++ it "displays the going count" do+ DiscoursePostEvent::Invitee.create!(+ post_id: post_1.id,+ user_id: Fabricate(:user).id,+ status: DiscoursePostEvent::Invitee.statuses[:going],+ )++ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("1 going")+ end++ it "displays a zero going count when there are no attendees" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).to include("0 going")+ end+ end++ context "when the event is a standalone event" do+ let(:post_1) { create_post_with_event(user_1, 'status="standalone"') }++ it "does not display a going count" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).not_to include("going")+ end+ end++ context "when the event is expired and recurring" do+ let(:post_1) do+ PostCreator.create!(+ user_1,+ title: "Sell a boat party ##{SecureRandom.alphanumeric}",+ raw:+ "[event start=\"2018-05-01 10:00\" recurrence=\"every_week\" recurrence-until=\"2018-05-20 10:00\"]\n[/event]",+ ).reload+ end++ it "does not display a stale date (matching the on-site card)" do+ cooked = PrettyText.cook(post_1.raw)+ result = PrettyText.format_for_email(cooked, post_1)++ expect(result).not_to include("May 1, 2018")+ expect(result).to include(">-</td>")+ end+ end++ context "when the renderer raises" do+ let(:post_1) { create_post_with_event(user_1) }++ it "does not abort the rest of the email rendering" do+ cooked = PrettyText.cook(post_1.raw)+ DiscoursePostEvent::EmailRenderer.stubs(:render).raises(StandardError.new("boom"))++ expect { PrettyText.format_for_email(cooked, post_1) }.not_to raise_error+ end+ endendendend