Skip to content

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

MT: Import closed flag, image and allowed groups of events

Gerhard Schlager6c34eb7a7349
diff --git a/script/bulk_import/base.rb b/script/bulk_import/base.rb
index 8076fbfcc44..3a447d5fd2f 100644
--- a/script/bulk_import/base.rb
+++ b/script/bulk_import/base.rb
@@ -950,6 +950,8 @@ class BulkImport::Base
recurrence
timezone
minimal
+ closed
+ image_upload_id
]
POST_EVENT_INVITEE_COLUMNS = %i[post_id user_id status notified recurring created_at updated_at]
diff --git a/script/bulk_import/generic_bulk.rb b/script/bulk_import/generic_bulk.rb
index 571f5682dd4..5a949a12e89 100644
--- a/script/bulk_import/generic_bulk.rb
+++ b/script/bulk_import/generic_bulk.rb
@@ -2367,6 +2367,7 @@ class BulkImport::Generic < BulkImport::Base
puts "", "Importing posts..."
start_delta_entity(:posts, "posts", :posts, @last_post_id)
+ load_event_lookups
update_delta_posts if delta_import?
posts = query(<<~SQL)
@@ -2699,6 +2700,8 @@ class BulkImport::Generic < BulkImport::Base
end
url = event["url"]
location = event_location(event)
+ allowed_groups = event_allowed_group_names(event)
+ image = @event_image_urls_by_upload_id[event_image_upload_id(event)]
custom_fields = event["custom_fields"] ? JSON.parse(event["custom_fields"]) : nil
text = +"[event"
@@ -2710,6 +2713,9 @@ class BulkImport::Generic < BulkImport::Base
text << bbcode_attribute("name", name) if name
text << bbcode_attribute("url", url) if url
text << bbcode_attribute("location", location) if location
+ text << %{ allowed-groups="#{allowed_groups.join(",")}"} if allowed_groups.present?
+ text << %{ image="#{image}"} if image
+ text << %{ closed="true"} if to_boolean(event["closed"])
custom_fields&.each { |key, value| text << bbcode_attribute(key, value) }
text << "]\n"
text << "[/event]\n"
@@ -2725,6 +2731,59 @@ class BulkImport::Generic < BulkImport::Base
time.in_time_zone(timezone).strftime("%Y-%m-%d %H:%M")
end
+ # The plugin only keeps invited groups on private events. Public events invite
+ # everyone and standalone events nobody.
+ def event_allowed_group_names(event)
+ return [] if event["status"] != DiscourseEvents::Events::Event.statuses[:private]
+
+ event_allowed_group_ids(event).filter_map { |id| @group_names_by_id[id] }
+ end
+
+ def event_allowed_group_ids(event)
+ return [] if event["allowed_group_ids"].blank?
+
+ JSON.parse(event["allowed_group_ids"]).filter_map { |id| group_id_from_imported_id(id) }
+ end
+
+ # Events are converted while rows are copied, when the connection can't run queries.
+ def load_event_lookups
+ return unless defined?(DiscourseEvents::Events)
+
+ @group_names_by_id = Group.pluck(:id, :name).to_h
+
+ upload_ids =
+ if table_column_names("events").include?("image_upload_id")
+ query(
+ "SELECT DISTINCT image_upload_id FROM events WHERE image_upload_id IS NOT NULL",
+ ) { |rows| rows.filter_map { |row| upload_id_from_original_id(row["image_upload_id"]) } }
+ else
+ []
+ end
+ @event_image_urls_by_upload_id =
+ Upload.where(id: upload_ids).to_h { |upload| [upload.id, upload.short_url] }
+ end
+
+ def log_event_allowed_group_issues(event)
+ return if event["allowed_group_ids"].blank?
+
+ if event["status"] != DiscourseEvents::Events::Event.statuses[:private]
+ log_import_issue("event allowed groups ignored (event isn't private)", "event #{event["id"]}")
+ return
+ end
+
+ missing = JSON.parse(event["allowed_group_ids"]).reject { |id| group_id_from_imported_id(id) }
+ return if missing.empty?
+
+ log_import_issue(
+ "event allowed groups not found",
+ "#{missing.join(", ")} (event #{event["id"]})",
+ )
+ end
+
+ def event_image_upload_id(event)
+ upload_id_from_original_id(event["image_upload_id"]) if event["image_upload_id"].present?
+ end
+
# Line breaks would end the BBCode tag, and the plugin stores at most 1000 characters.
def event_location(event)
event["location"]&.squish.presence&.[](0..999)
@@ -3869,10 +3928,25 @@ class BulkImport::Generic < BulkImport::Base
SQL
puts " Import took #{(Time.now - start_time).to_i} seconds."
+ import_event_upload_references
+
import_content_upload_references("posts")
import_content_upload_references("chat_messages")
end
+ def import_event_upload_references
+ return unless defined?(DiscourseEvents::Events)
+
+ puts "", "Importing upload references for events..."
+ DB.exec(<<~SQL, target_type: DiscourseEvents::Events::Event.name)
+ INSERT INTO upload_references (upload_id, target_type, target_id, created_at, updated_at)
+ SELECT image_upload_id, :target_type, id, NOW(), NOW()
+ FROM discourse_post_event_events
+ WHERE image_upload_id IS NOT NULL
+ ON CONFLICT DO NOTHING
+ SQL
+ end
+
def import_content_upload_references(type)
if CONTENT_UPLOAD_REFERENCE_TYPES.exclude?(type)
puts " Skipping upload references import for #{type} because it's unsupported"
@@ -4392,10 +4466,11 @@ class BulkImport::Generic < BulkImport::Base
SQL
default_custom_fields = "{}"
- public_group_invitees = "{#{DiscourseEvents::Events::Event::PUBLIC_GROUP}}"
- standalone_invitees = "{}"
+ statuses = DiscourseEvents::Events::Event.statuses
+ array_encoder = PG::TextEncoder::Array.new
existing_events = DiscourseEvents::Events::Event.pluck(:id).to_set
+ load_event_lookups
create_post_events(post_events) do |row|
post_id = post_id_from_imported_id(row["post_id"])
@@ -4409,6 +4484,18 @@ class BulkImport::Generic < BulkImport::Base
)
end
+ raw_invitees =
+ case row["status"]
+ when statuses[:public]
+ [DiscourseEvents::Events::Event::PUBLIC_GROUP]
+ when statuses[:private]
+ event_allowed_group_names(row)
+ else
+ []
+ end
+
+ log_event_allowed_group_issues(row)
+
{
id: post_id,
status: row["status"],
@@ -4419,17 +4506,32 @@ class BulkImport::Generic < BulkImport::Base
location: event_location(row),
custom_fields: row["custom_fields"] || default_custom_fields,
timezone:,
- raw_invitees:
- (
- if row["status"] == DiscourseEvents::Events::Event.statuses[:public]
- public_group_invitees
- else
- standalone_invitees
- end
- ),
+ raw_invitees: array_encoder.encode(raw_invitees),
+ closed: to_boolean(row["closed"]),
+ image_upload_id: event_image_upload_id(row),
}
end
+ # Like Event#sync_image_to_post_and_topic, without waiting for a rebake.
+ DB.exec(<<~SQL)
+ UPDATE posts p
+ SET image_upload_id = e.image_upload_id
+ FROM discourse_post_event_events e
+ WHERE e.id = p.id
+ AND e.image_upload_id IS NOT NULL
+ AND p.image_upload_id IS DISTINCT FROM e.image_upload_id
+ SQL
+ DB.exec(<<~SQL)
+ UPDATE topics t
+ SET image_upload_id = p.image_upload_id
+ FROM posts p
+ JOIN discourse_post_event_events e ON e.id = p.id
+ WHERE p.topic_id = t.id
+ AND p.post_number = 1
+ AND e.image_upload_id IS NOT NULL
+ AND t.image_upload_id IS DISTINCT FROM e.image_upload_id
+ SQL
+
puts "", "Importing event dates..."
post_events.reset
@@ -4494,30 +4596,54 @@ class BulkImport::Generic < BulkImport::Base
puts "", "Importing event invitees..."
invitees = query(<<~SQL)
- SELECT event_invitees.*, events.post_id AS event_post_id, events.status AS event_status
+ SELECT event_invitees.*, events.post_id AS event_post_id
FROM event_invitees
JOIN events ON events.id = event_invitees.event_id
ORDER BY event_invitees.event_id, event_invitees.user_id
SQL
statuses = DiscourseEvents::Events::Invitee.statuses
- public_status = DiscourseEvents::Events::Event.statuses[:public]
+ event_statuses = DiscourseEvents::Events::Event.statuses
+ events =
+ DiscourseEvents::Events::Event
+ .pluck(:id, :status, :raw_invitees)
+ .to_h { |id, status, groups| [id, { status:, groups: groups || [] }] }
+ private_event_groups =
+ events.values.filter_map do |event|
+ event[:groups] if event[:status] == event_statuses[:private]
+ end
+ group_members =
+ GroupUser
+ .joins(:group)
+ .where(groups: { name: private_event_groups.flatten.uniq })
+ .pluck(:user_id, "groups.name")
+ .to_set
# The default scope hides suspended, silenced and staged users.
existing_invitees = DiscourseEvents::Events::Invitee.unscoped.pluck(:post_id, :user_id).to_set
create_event_invitees(invitees) do |row|
post_id = post_id_from_imported_id(row["event_post_id"])
user_id = user_id_from_imported_id(row["user_id"])
- next unless post_id && user_id
+ event = events[post_id]
+ next unless event && user_id
- # The plugin removes invitees from standalone events and from private events
- # without invited groups, which is all the importer creates besides public ones.
- if row["event_status"] != public_status
+ # The plugin removes invitees from standalone events, and from private events
+ # when they aren't in one of the allowed groups.
+ case event[:status]
+ when event_statuses[:standalone]
log_import_issue(
- "event invitee skipped (event isn't public)",
+ "event invitee skipped (standalone event)",
"user #{row["user_id"]} of event #{row["event_id"]}",
)
next
+ when event_statuses[:private]
+ if event[:groups].none? { |group| group_members.include?([user_id, group]) }
+ log_import_issue(
+ "event invitee skipped (not in the event's allowed groups)",
+ "user #{row["user_id"]} of event #{row["event_id"]}",
+ )
+ next
+ end
end
status = row["status"] || statuses[:going]
diff --git a/spec/script/bulk_import/generic_bulk_spec.rb b/spec/script/bulk_import/generic_bulk_spec.rb
index 1a1a3c4af48..056c17a9dff 100644
--- a/spec/script/bulk_import/generic_bulk_spec.rb
+++ b/spec/script/bulk_import/generic_bulk_spec.rb
@@ -662,6 +662,9 @@ if generic_import_dependencies_available
fab!(:invalid_post, :post)
fab!(:attendee, :user)
fab!(:other_attendee, :user)
+ fab!(:members) { Fabricate(:group, name: "members", users: [attendee]) }
+ fab!(:staff_group) { Fabricate(:group, name: "staff_only") }
+ fab!(:image, :upload)
let(:source_db) { SQLite3::Database.new(":memory:", results_as_hash: true) }
let(:import_issue_log_path) { File.join(Dir.mktmpdir, "issues.log") }
@@ -677,6 +680,8 @@ if generic_import_dependencies_available
[vienna_post, untimed_post, invalid_post].to_h { |post| [post.id, post.topic_id] },
)
instance.instance_variable_set(:@users, { 10 => attendee.id, 11 => other_attendee.id })
+ instance.instance_variable_set(:@groups, { 50 => members.id, 51 => staff_group.id })
+ instance.instance_variable_set(:@uploads_mapping, { "70" => image.id.to_s })
instance.instance_variable_set(:@import_issue_log_path, import_issue_log_path)
instance.instance_variable_set(
:@raw_connection,
@@ -687,6 +692,7 @@ if generic_import_dependencies_available
end
let(:public_status) { DiscourseEvents::Events::Event.statuses[:public] }
let(:standalone_status) { DiscourseEvents::Events::Event.statuses[:standalone] }
+ let(:private_status) { DiscourseEvents::Events::Event.statuses[:private] }
before { skip "requires the events plugin" unless defined?(DiscourseEvents::Events) }
@@ -697,7 +703,7 @@ if generic_import_dependencies_available
CREATE TABLE events (
id INTEGER, post_id INTEGER, status INTEGER, starts_at DATETIME, ends_at DATETIME,
name TEXT, url TEXT, custom_fields JSON_TEXT
- #{", location TEXT, timezone TEXT" if new_columns}
+ #{", location TEXT, timezone TEXT, closed BOOLEAN, image_upload_id TEXT, allowed_group_ids JSON_TEXT" if new_columns}
)
SQL
end
@@ -720,16 +726,52 @@ if generic_import_dependencies_available
source_db.get_first_row("SELECT * FROM events WHERE id = ?", id)
end
+ def event_bbcode(id)
+ importer.load_event_lookups
+ importer.event_bbcode(event_row(id))
+ end
+
def import_issues
File.exist?(import_issue_log_path) ? File.read(import_issue_log_path) : ""
end
+ describe "#import_posts" do
+ it "loads the event lookups before updating delta posts" do
+ create_events_table
+ insert_event(1, image_upload_id: "70")
+ posts =
+ Class
+ .new do
+ def close
+ end
+ end
+ .new
+ allow(importer).to receive_messages(
+ puts: nil,
+ start_delta_entity: nil,
+ finish_delta_entity: nil,
+ create_posts: nil,
+ delta_import?: true,
+ )
+ allow(importer).to receive(:query).and_call_original
+ allow(importer).to receive(:query).with(/FROM posts/).and_return(posts)
+ bbcode = nil
+ allow(importer).to receive(:update_delta_posts) {
+ bbcode = importer.event_bbcode(event_row(1))
+ }
+
+ importer.import_posts
+
+ expect(bbcode).to include(%{ image="#{image.short_url}"})
+ end
+ end
+
describe "#event_bbcode" do
it "writes start and end as local times in the event's timezone" do
create_events_table
insert_event(1, timezone: "Europe/Vienna")
- bbcode = importer.event_bbcode(event_row(1))
+ bbcode = event_bbcode(1)
expect(bbcode).to include(
'start="2026-07-01 10:00" end="2026-07-01 11:30" timezone="Europe/Vienna"',
@@ -745,7 +787,7 @@ if generic_import_dependencies_available
insert_event(3, timezone: "+01:00")
[2, 3].each do |id|
- expect(importer.event_bbcode(event_row(id))).to include(
+ expect(event_bbcode(id)).to include(
'start="2026-07-01 08:00" end="2026-07-01 09:30" timezone="UTC"',
)
end
@@ -756,8 +798,35 @@ if generic_import_dependencies_available
insert_event(1, location: "Town Hall\nRoom 1")
insert_event(2, location: "x" * 1200)
- expect(importer.event_bbcode(event_row(1))).to include(%{ location="Town Hall Room 1"})
- expect(importer.event_bbcode(event_row(2))).to include(%{ location="#{"x" * 1000}"})
+ expect(event_bbcode(1)).to include(%{ location="Town Hall Room 1"})
+ expect(event_bbcode(2)).to include(%{ location="#{"x" * 1000}"})
+ end
+
+ it "writes allowed groups of private events, the image and the closed flag" do
+ SiteSetting.discourse_post_event_enabled = true
+ create_events_table
+ insert_event(
+ 1,
+ status: private_status,
+ allowed_group_ids: [50, 51, 52].to_json,
+ image_upload_id: "70",
+ closed: 1,
+ )
+ insert_event(2, status: public_status, allowed_group_ids: [50].to_json, closed: 0)
+
+ private_bbcode = event_bbcode(1)
+ public_bbcode = event_bbcode(2)
+
+ expect(
+ DiscourseEvents::Events::Parser.extract_events(
+ Fabricate.build(:post, raw: private_bbcode),
+ ).first,
+ ).to include(
+ "allowed-groups": "members,staff_only",
+ image: image.short_url,
+ closed: "true",
+ )
+ expect(public_bbcode).not_to include("allowed-groups", "image", "closed")
end
it "quotes attributes so the plugin reads them back unchanged" do
@@ -772,7 +841,7 @@ if generic_import_dependencies_available
custom_fields: { room: %{"A" 'B'} }.to_json,
)
- bbcode = importer.event_bbcode(event_row(1))
+ bbcode = event_bbcode(1)
post = Fabricate.build(:post, raw: bbcode)
expect(bbcode).to include(%{ location=“The "Old" Town Hall, 'Room' «1»”})
@@ -787,7 +856,7 @@ if generic_import_dependencies_available
create_events_table(new_columns: false)
insert_event(1)
- bbcode = importer.event_bbcode(event_row(1))
+ bbcode = event_bbcode(1)
expect(bbcode).to include('timezone="UTC"')
expect(bbcode).not_to include("location")
@@ -846,6 +915,47 @@ if generic_import_dependencies_available
end
end
+ describe "#import_post_events with groups, image and closed flag" do
+ it "imports them and logs groups that can't be used" do
+ create_events_table
+ insert_event(
+ 1,
+ status: private_status,
+ allowed_group_ids: [50, 52].to_json,
+ image_upload_id: "70",
+ closed: 1,
+ )
+ insert_event(2, status: public_status, allowed_group_ids: [51].to_json)
+ insert_event(3, status: standalone_status)
+
+ importer.import_post_events
+ importer.import_event_upload_references
+
+ expect(
+ DiscourseEvents::Events::Event.where(
+ id: [vienna_post.id, untimed_post.id, invalid_post.id],
+ ).pluck(:id, :raw_invitees, :closed, :image_upload_id),
+ ).to contain_exactly(
+ [vienna_post.id, ["members"], true, image.id],
+ [untimed_post.id, [DiscourseEvents::Events::Event::PUBLIC_GROUP], false, nil],
+ [invalid_post.id, [], false, nil],
+ )
+ expect(vienna_post.reload.image_upload_id).to eq(image.id)
+ expect(vienna_post.topic.reload.image_upload_id).to eq(image.id)
+ expect(
+ UploadReference.where(
+ upload: image,
+ target_type: "DiscourseEvents::Events::Event",
+ target_id: vienna_post.id,
+ ),
+ ).to exist
+ expect(import_issues.lines).to contain_exactly(
+ "[event allowed groups not found] 52 (event 1)\n",
+ "[event allowed groups ignored (event isn't private)] event 2\n",
+ )
+ end
+ end
+
describe "#import_event_invitees" do
def create_invitees_table
source_db.execute(<<~SQL)
@@ -879,6 +989,7 @@ if generic_import_dependencies_available
insert_invitee(101, 10)
insert_invitee(101, 11, status: interested)
+ importer.import_post_events
importer.import_event_invitees
importer.import_event_invitees
@@ -891,23 +1002,30 @@ if generic_import_dependencies_available
)
end
- it "skips invitees that can't be imported" do
+ it "skips invitees the plugin wouldn't keep" do
create_events_table
create_invitees_table
insert_event(1, status: public_status)
insert_event(2, status: standalone_status)
+ insert_event(3, status: private_status, allowed_group_ids: [50].to_json)
insert_event(99, status: public_status)
insert_invitee(1, 99)
insert_invitee(99, 10)
insert_invitee(2, 10)
insert_invitee(1, 11, status: 42)
+ insert_invitee(3, 10)
+ insert_invitee(3, 11)
+ importer.import_post_events
importer.import_event_invitees
- expect(imported_invitees).to be_empty
+ expect(imported_invitees.map { |invitee| invitee.first(2) }).to eq(
+ [[invalid_post.id, attendee.id]],
+ )
expect(import_issues.lines).to contain_exactly(
- "[event invitee skipped (event isn't public)] user 10 of event 2\n",
+ "[event invitee skipped (standalone event)] user 10 of event 2\n",
"[event invitee skipped (unknown status)] status 42 of user 11 in event 1\n",
+ "[event invitee skipped (not in the event's allowed groups)] user 11 of event 3\n",
)
end