mirror of
https://github.com/discourse/discourse.git
synced 2025-05-21 18:12:32 +08:00
DEV: Apply syntax_tree formatting to script/*
This commit is contained in:
@ -12,16 +12,14 @@
|
||||
# that was done using import_scripts/support/convert_mysql_xml_to_mysql.rb
|
||||
#
|
||||
|
||||
require 'mysql2'
|
||||
require 'csv'
|
||||
require 'reverse_markdown'
|
||||
require "mysql2"
|
||||
require "csv"
|
||||
require "reverse_markdown"
|
||||
require File.expand_path(File.dirname(__FILE__) + "/base.rb")
|
||||
require 'htmlentities'
|
||||
require "htmlentities"
|
||||
|
||||
# remove table conversion
|
||||
[:table, :td, :tr, :th, :thead, :tbody].each do |tag|
|
||||
ReverseMarkdown::Converters.unregister(tag)
|
||||
end
|
||||
%i[table td tr th thead tbody].each { |tag| ReverseMarkdown::Converters.unregister(tag) }
|
||||
|
||||
class ImportScripts::Lithium < ImportScripts::Base
|
||||
BATCH_SIZE = 1000
|
||||
@ -29,11 +27,11 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
# CHANGE THESE BEFORE RUNNING THE IMPORTER
|
||||
DATABASE = "wd"
|
||||
PASSWORD = "password"
|
||||
AVATAR_DIR = '/tmp/avatars'
|
||||
ATTACHMENT_DIR = '/tmp/attachments'
|
||||
UPLOAD_DIR = '/tmp/uploads'
|
||||
AVATAR_DIR = "/tmp/avatars"
|
||||
ATTACHMENT_DIR = "/tmp/attachments"
|
||||
UPLOAD_DIR = "/tmp/uploads"
|
||||
|
||||
OLD_DOMAIN = 'community.wd.com'
|
||||
OLD_DOMAIN = "community.wd.com"
|
||||
|
||||
TEMP = ""
|
||||
|
||||
@ -44,11 +42,10 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
{ name: "user_field_3", profile: "industry" },
|
||||
]
|
||||
|
||||
LITHIUM_PROFILE_FIELDS = "'profile.jobtitle', 'profile.company', 'profile.industry', 'profile.location'"
|
||||
LITHIUM_PROFILE_FIELDS =
|
||||
"'profile.jobtitle', 'profile.company', 'profile.industry', 'profile.location'"
|
||||
|
||||
USERNAME_MAPPINGS = {
|
||||
"admins": "admin_user"
|
||||
}.with_indifferent_access
|
||||
USERNAME_MAPPINGS = { admins: "admin_user" }.with_indifferent_access
|
||||
|
||||
def initialize
|
||||
super
|
||||
@ -57,16 +54,16 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
|
||||
@htmlentities = HTMLEntities.new
|
||||
|
||||
@client = Mysql2::Client.new(
|
||||
host: "localhost",
|
||||
username: "root",
|
||||
password: PASSWORD,
|
||||
database: DATABASE
|
||||
)
|
||||
@client =
|
||||
Mysql2::Client.new(
|
||||
host: "localhost",
|
||||
username: "root",
|
||||
password: PASSWORD,
|
||||
database: DATABASE,
|
||||
)
|
||||
end
|
||||
|
||||
def execute
|
||||
|
||||
@max_start_id = Post.maximum(:id)
|
||||
|
||||
import_groups
|
||||
@ -94,10 +91,7 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
SQL
|
||||
|
||||
create_groups(groups) do |group|
|
||||
{
|
||||
id: group["name"],
|
||||
name: @htmlentities.decode(group["name"]).strip
|
||||
}
|
||||
{ id: group["name"], name: @htmlentities.decode(group["name"]).strip }
|
||||
end
|
||||
end
|
||||
|
||||
@ -106,7 +100,10 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
|
||||
user_count = mysql_query("SELECT COUNT(*) count FROM users").first["count"]
|
||||
avatar_files = Dir.entries(AVATAR_DIR)
|
||||
duplicate_emails = mysql_query("SELECT email_lower FROM users GROUP BY email_lower HAVING COUNT(email_lower) > 1").map { |e| [e["email_lower"], 0] }.to_h
|
||||
duplicate_emails =
|
||||
mysql_query(
|
||||
"SELECT email_lower FROM users GROUP BY email_lower HAVING COUNT(email_lower) > 1",
|
||||
).map { |e| [e["email_lower"], 0] }.to_h
|
||||
|
||||
batches(BATCH_SIZE) do |offset|
|
||||
users = mysql_query <<-SQL
|
||||
@ -134,8 +131,8 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
|
||||
create_users(users, total: user_count, offset: offset) do |user|
|
||||
user_id = user["id"]
|
||||
profile = profiles.select { |p| p["user_id"] == user_id }
|
||||
result = profile.select { |p| p["param"] == "profile.location" }
|
||||
profile = profiles.select { |p| p["user_id"] == user_id }
|
||||
result = profile.select { |p| p["param"] == "profile.location" }
|
||||
location = result.count > 0 ? result.first["nvalue"] : nil
|
||||
username = user["login_canon"]
|
||||
username = USERNAME_MAPPINGS[username] if USERNAME_MAPPINGS[username].present?
|
||||
@ -158,31 +155,32 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
# title: @htmlentities.decode(user["usertitle"]).strip,
|
||||
# primary_group_id: group_id_from_imported_group_id(user["usergroupid"]),
|
||||
created_at: unix_time(user["registration_time"]),
|
||||
post_create_action: proc do |u|
|
||||
@old_username_to_new_usernames[user["login_canon"]] = u.username
|
||||
post_create_action:
|
||||
proc do |u|
|
||||
@old_username_to_new_usernames[user["login_canon"]] = u.username
|
||||
|
||||
# import user avatar
|
||||
sso_id = u.custom_fields["sso_id"]
|
||||
if sso_id.present?
|
||||
prefix = "#{AVATAR_DIR}/#{sso_id}_"
|
||||
file = get_file(prefix + "actual.jpeg")
|
||||
file ||= get_file(prefix + "profile.jpeg")
|
||||
# import user avatar
|
||||
sso_id = u.custom_fields["sso_id"]
|
||||
if sso_id.present?
|
||||
prefix = "#{AVATAR_DIR}/#{sso_id}_"
|
||||
file = get_file(prefix + "actual.jpeg")
|
||||
file ||= get_file(prefix + "profile.jpeg")
|
||||
|
||||
if file.present?
|
||||
upload = UploadCreator.new(file, file.path, type: "avatar").create_for(u.id)
|
||||
u.create_user_avatar unless u.user_avatar
|
||||
if file.present?
|
||||
upload = UploadCreator.new(file, file.path, type: "avatar").create_for(u.id)
|
||||
u.create_user_avatar unless u.user_avatar
|
||||
|
||||
if !u.user_avatar.contains_upload?(upload.id)
|
||||
u.user_avatar.update_columns(custom_upload_id: upload.id)
|
||||
if !u.user_avatar.contains_upload?(upload.id)
|
||||
u.user_avatar.update_columns(custom_upload_id: upload.id)
|
||||
|
||||
if u.uploaded_avatar_id.nil? ||
|
||||
!u.user_avatar.contains_upload?(u.uploaded_avatar_id)
|
||||
u.update_columns(uploaded_avatar_id: upload.id)
|
||||
if u.uploaded_avatar_id.nil? ||
|
||||
!u.user_avatar.contains_upload?(u.uploaded_avatar_id)
|
||||
u.update_columns(uploaded_avatar_id: upload.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end,
|
||||
}
|
||||
end
|
||||
end
|
||||
@ -226,7 +224,7 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
if attr[:user].present?
|
||||
fields[name] = user[attr[:user]]
|
||||
elsif attr[:profile].present? && profile.count > 0
|
||||
result = profile.select { |p| p["param"] == "profile.#{attr[:profile]}" }
|
||||
result = profile.select { |p| p["param"] == "profile.#{attr[:profile]}" }
|
||||
fields[name] = result.first["nvalue"] if result.count > 0
|
||||
end
|
||||
end
|
||||
@ -268,8 +266,16 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
imported_user.user_avatar.update(custom_upload_id: upload.id)
|
||||
imported_user.update(uploaded_avatar_id: upload.id)
|
||||
ensure
|
||||
file.close rescue nil
|
||||
file.unlind rescue nil
|
||||
begin
|
||||
file.close
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
begin
|
||||
file.unlind
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
def import_profile_background(old_user, imported_user)
|
||||
@ -295,8 +301,16 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
|
||||
imported_user.user_profile.upload_profile_background(upload)
|
||||
ensure
|
||||
file.close rescue nil
|
||||
file.unlink rescue nil
|
||||
begin
|
||||
file.close
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
begin
|
||||
file.unlink
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
def import_categories
|
||||
@ -310,14 +324,16 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
ORDER BY n.type_id DESC, n.node_id ASC
|
||||
SQL
|
||||
|
||||
categories = categories.map { |c| (c["name"] = c["c_title"] || c["b_title"] || c["display_id"]) && c }
|
||||
categories =
|
||||
categories.map { |c| (c["name"] = c["c_title"] || c["b_title"] || c["display_id"]) && c }
|
||||
|
||||
# To prevent duplicate category names
|
||||
categories = categories.map do |category|
|
||||
count = categories.to_a.count { |c| c["name"].present? && c["name"] == category["name"] }
|
||||
category["name"] << " (#{category["node_id"]})" if count > 1
|
||||
category
|
||||
end
|
||||
categories =
|
||||
categories.map do |category|
|
||||
count = categories.to_a.count { |c| c["name"].present? && c["name"] == category["name"] }
|
||||
category["name"] << " (#{category["node_id"]})" if count > 1
|
||||
category
|
||||
end
|
||||
|
||||
parent_categories = categories.select { |c| c["parent_node_id"] <= 2 }
|
||||
|
||||
@ -326,9 +342,7 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
id: category["node_id"],
|
||||
name: category["name"],
|
||||
position: category["position"],
|
||||
post_create_action: lambda do |record|
|
||||
after_category_create(record, category)
|
||||
end
|
||||
post_create_action: lambda { |record| after_category_create(record, category) },
|
||||
}
|
||||
end
|
||||
|
||||
@ -342,9 +356,7 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
name: category["name"],
|
||||
position: category["position"],
|
||||
parent_category_id: category_id_from_imported_category_id(category["parent_node_id"]),
|
||||
post_create_action: lambda do |record|
|
||||
after_category_create(record, category)
|
||||
end
|
||||
post_create_action: lambda { |record| after_category_create(record, category) },
|
||||
}
|
||||
end
|
||||
end
|
||||
@ -371,7 +383,6 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
def staff_guardian
|
||||
@ -386,8 +397,12 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
SiteSetting.max_tags_per_topic = 10
|
||||
SiteSetting.max_tag_length = 100
|
||||
|
||||
topic_count = mysql_query("SELECT COUNT(*) count FROM message2 where id = root_id").first["count"]
|
||||
topic_tags = mysql_query("SELECT e.target_id, GROUP_CONCAT(l.tag_text SEPARATOR ',') tags FROM tag_events_label_message e LEFT JOIN tags_label l ON e.tag_id = l.tag_id GROUP BY e.target_id")
|
||||
topic_count =
|
||||
mysql_query("SELECT COUNT(*) count FROM message2 where id = root_id").first["count"]
|
||||
topic_tags =
|
||||
mysql_query(
|
||||
"SELECT e.target_id, GROUP_CONCAT(l.tag_text SEPARATOR ',') tags FROM tag_events_label_message e LEFT JOIN tags_label l ON e.tag_id = l.tag_id GROUP BY e.target_id",
|
||||
)
|
||||
|
||||
batches(BATCH_SIZE) do |offset|
|
||||
topics = mysql_query <<-SQL
|
||||
@ -405,7 +420,6 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
next if all_records_exist? :posts, topics.map { |topic| "#{topic["node_id"]} #{topic["id"]}" }
|
||||
|
||||
create_posts(topics, total: topic_count, offset: offset) do |topic|
|
||||
|
||||
category_id = category_id_from_imported_category_id(topic["node_id"])
|
||||
deleted_at = topic["deleted"] == 1 ? topic["row_version"] : nil
|
||||
raw = topic["body"]
|
||||
@ -420,24 +434,31 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
created_at: unix_time(topic["post_date"]),
|
||||
deleted_at: deleted_at,
|
||||
views: topic["views"],
|
||||
custom_fields: { import_unique_id: topic["unique_id"] },
|
||||
custom_fields: {
|
||||
import_unique_id: topic["unique_id"],
|
||||
},
|
||||
import_mode: true,
|
||||
post_create_action: proc do |post|
|
||||
result = topic_tags.select { |t| t["target_id"] == topic["unique_id"] }
|
||||
if result.count > 0
|
||||
tag_names = result.first["tags"].split(",")
|
||||
DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)
|
||||
end
|
||||
end
|
||||
post_create_action:
|
||||
proc do |post|
|
||||
result = topic_tags.select { |t| t["target_id"] == topic["unique_id"] }
|
||||
if result.count > 0
|
||||
tag_names = result.first["tags"].split(",")
|
||||
DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)
|
||||
end
|
||||
end,
|
||||
}
|
||||
else
|
||||
message = "Unknown"
|
||||
message = "Category '#{category_id}' not exist" if category_id.blank?
|
||||
message = "Topic 'body' is empty" if raw.blank?
|
||||
PluginStoreRow.find_or_create_by(plugin_name: "topic_import_log", key: topic["unique_id"].to_s, value: message, type_name: 'String')
|
||||
PluginStoreRow.find_or_create_by(
|
||||
plugin_name: "topic_import_log",
|
||||
key: topic["unique_id"].to_s,
|
||||
value: message,
|
||||
type_name: "String",
|
||||
)
|
||||
nil
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
@ -446,9 +467,13 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
end
|
||||
|
||||
def import_posts
|
||||
|
||||
post_count = mysql_query("SELECT COUNT(*) count FROM message2
|
||||
WHERE id <> root_id").first["count"]
|
||||
post_count =
|
||||
mysql_query(
|
||||
"SELECT COUNT(*) count FROM message2
|
||||
WHERE id <> root_id",
|
||||
).first[
|
||||
"count"
|
||||
]
|
||||
|
||||
puts "", "importing posts... (#{post_count})"
|
||||
|
||||
@ -465,11 +490,18 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
|
||||
break if posts.size < 1
|
||||
|
||||
next if all_records_exist? :posts, posts.map { |post| "#{post["node_id"]} #{post["root_id"]} #{post["id"]}" }
|
||||
if all_records_exist? :posts,
|
||||
posts.map { |post|
|
||||
"#{post["node_id"]} #{post["root_id"]} #{post["id"]}"
|
||||
}
|
||||
next
|
||||
end
|
||||
|
||||
create_posts(posts, total: post_count, offset: offset) do |post|
|
||||
raw = post["raw"]
|
||||
next unless topic = topic_lookup_from_imported_post_id("#{post["node_id"]} #{post["root_id"]}")
|
||||
unless topic = topic_lookup_from_imported_post_id("#{post["node_id"]} #{post["root_id"]}")
|
||||
next
|
||||
end
|
||||
|
||||
deleted_at = topic["deleted"] == 1 ? topic["row_version"] : nil
|
||||
raw = post["body"]
|
||||
@ -482,17 +514,27 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
raw: raw,
|
||||
created_at: unix_time(post["post_date"]),
|
||||
deleted_at: deleted_at,
|
||||
custom_fields: { import_unique_id: post["unique_id"] },
|
||||
import_mode: true
|
||||
custom_fields: {
|
||||
import_unique_id: post["unique_id"],
|
||||
},
|
||||
import_mode: true,
|
||||
}
|
||||
|
||||
if parent = topic_lookup_from_imported_post_id("#{post["node_id"]} #{post["root_id"]} #{post["parent_id"]}")
|
||||
if parent =
|
||||
topic_lookup_from_imported_post_id(
|
||||
"#{post["node_id"]} #{post["root_id"]} #{post["parent_id"]}",
|
||||
)
|
||||
new_post[:reply_to_post_number] = parent[:post_number]
|
||||
end
|
||||
|
||||
new_post
|
||||
else
|
||||
PluginStoreRow.find_or_create_by(plugin_name: "post_import_log", key: post["unique_id"].to_s, value: "Post 'body' is empty", type_name: 'String')
|
||||
PluginStoreRow.find_or_create_by(
|
||||
plugin_name: "post_import_log",
|
||||
key: post["unique_id"].to_s,
|
||||
value: "Post 'body' is empty",
|
||||
type_name: "String",
|
||||
)
|
||||
nil
|
||||
end
|
||||
end
|
||||
@ -521,37 +563,40 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
"catwink" => "wink",
|
||||
"catfrustrated" => "grumpycat",
|
||||
"catembarrassed" => "kissing_cat",
|
||||
"catlol" => "joy_cat"
|
||||
"catlol" => "joy_cat",
|
||||
}
|
||||
|
||||
def import_likes
|
||||
puts "\nimporting likes..."
|
||||
|
||||
sql = "select source_id user_id, target_id post_id, row_version created_at from tag_events_score_message"
|
||||
sql =
|
||||
"select source_id user_id, target_id post_id, row_version created_at from tag_events_score_message"
|
||||
results = mysql_query(sql)
|
||||
|
||||
puts "loading unique id map"
|
||||
existing_map = {}
|
||||
PostCustomField.where(name: 'import_unique_id').pluck(:post_id, :value).each do |post_id, import_id|
|
||||
existing_map[import_id] = post_id
|
||||
end
|
||||
PostCustomField
|
||||
.where(name: "import_unique_id")
|
||||
.pluck(:post_id, :value)
|
||||
.each { |post_id, import_id| existing_map[import_id] = post_id }
|
||||
|
||||
puts "loading data into temp table"
|
||||
DB.exec("create temp table like_data(user_id int, post_id int, created_at timestamp without time zone)")
|
||||
DB.exec(
|
||||
"create temp table like_data(user_id int, post_id int, created_at timestamp without time zone)",
|
||||
)
|
||||
PostAction.transaction do
|
||||
results.each do |result|
|
||||
|
||||
result["user_id"] = user_id_from_imported_user_id(result["user_id"].to_s)
|
||||
result["post_id"] = existing_map[result["post_id"].to_s]
|
||||
|
||||
next unless result["user_id"] && result["post_id"]
|
||||
|
||||
DB.exec("INSERT INTO like_data VALUES (:user_id,:post_id,:created_at)",
|
||||
DB.exec(
|
||||
"INSERT INTO like_data VALUES (:user_id,:post_id,:created_at)",
|
||||
user_id: result["user_id"],
|
||||
post_id: result["post_id"],
|
||||
created_at: result["created_at"]
|
||||
created_at: result["created_at"],
|
||||
)
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
@ -616,31 +661,28 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
end
|
||||
|
||||
def import_accepted_answers
|
||||
|
||||
puts "\nimporting accepted answers..."
|
||||
|
||||
sql = "select unique_id post_id from message2 where (attributes & 0x4000 ) != 0 and deleted = 0;"
|
||||
sql =
|
||||
"select unique_id post_id from message2 where (attributes & 0x4000 ) != 0 and deleted = 0;"
|
||||
results = mysql_query(sql)
|
||||
|
||||
puts "loading unique id map"
|
||||
existing_map = {}
|
||||
PostCustomField.where(name: 'import_unique_id').pluck(:post_id, :value).each do |post_id, import_id|
|
||||
existing_map[import_id] = post_id
|
||||
end
|
||||
PostCustomField
|
||||
.where(name: "import_unique_id")
|
||||
.pluck(:post_id, :value)
|
||||
.each { |post_id, import_id| existing_map[import_id] = post_id }
|
||||
|
||||
puts "loading data into temp table"
|
||||
DB.exec("create temp table accepted_data(post_id int primary key)")
|
||||
PostAction.transaction do
|
||||
results.each do |result|
|
||||
|
||||
result["post_id"] = existing_map[result["post_id"].to_s]
|
||||
|
||||
next unless result["post_id"]
|
||||
|
||||
DB.exec("INSERT INTO accepted_data VALUES (:post_id)",
|
||||
post_id: result["post_id"]
|
||||
)
|
||||
|
||||
DB.exec("INSERT INTO accepted_data VALUES (:post_id)", post_id: result["post_id"])
|
||||
end
|
||||
end
|
||||
|
||||
@ -679,7 +721,6 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
end
|
||||
|
||||
def import_pms
|
||||
|
||||
puts "", "importing pms..."
|
||||
|
||||
puts "determining participation records"
|
||||
@ -702,24 +743,20 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
note_to_subject = {}
|
||||
subject_to_first_note = {}
|
||||
|
||||
mysql_query("SELECT note_id, subject, sender_user_id FROM tblia_notes_content order by note_id").each do |row|
|
||||
mysql_query(
|
||||
"SELECT note_id, subject, sender_user_id FROM tblia_notes_content order by note_id",
|
||||
).each do |row|
|
||||
user_id = user_id_from_imported_user_id(row["sender_user_id"])
|
||||
ary = (users[row["note_id"]] ||= Set.new)
|
||||
if user_id
|
||||
ary << user_id
|
||||
end
|
||||
note_to_subject[row["note_id"]] = row["subject"]
|
||||
ary = (users[row["note_id"]] ||= Set.new)
|
||||
ary << user_id if user_id
|
||||
note_to_subject[row["note_id"]] = row["subject"]
|
||||
|
||||
if row["subject"] !~ /^Re: /
|
||||
subject_to_first_note[[row["subject"], ary]] ||= row["note_id"]
|
||||
end
|
||||
subject_to_first_note[[row["subject"], ary]] ||= row["note_id"] if row["subject"] !~ /^Re: /
|
||||
end
|
||||
|
||||
puts "Loading user_id to username map"
|
||||
user_map = {}
|
||||
User.pluck(:id, :username).each do |id, username|
|
||||
user_map[id] = username
|
||||
end
|
||||
User.pluck(:id, :username).each { |id, username| user_map[id] = username }
|
||||
|
||||
topic_count = mysql_query("SELECT COUNT(*) count FROM tblia_notes_content").first["count"]
|
||||
|
||||
@ -737,8 +774,8 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
next if all_records_exist? :posts, topics.map { |topic| "pm_#{topic["note_id"]}" }
|
||||
|
||||
create_posts(topics, total: topic_count, offset: offset) do |topic|
|
||||
|
||||
user_id = user_id_from_imported_user_id(topic["sender_user_id"]) || Discourse::SYSTEM_USER_ID
|
||||
user_id =
|
||||
user_id_from_imported_user_id(topic["sender_user_id"]) || Discourse::SYSTEM_USER_ID
|
||||
participants = users[topic["note_id"]]
|
||||
|
||||
usernames = (participants - [user_id]).map { |id| user_map[id] }
|
||||
@ -763,48 +800,54 @@ class ImportScripts::Lithium < ImportScripts::Base
|
||||
user_id: user_id,
|
||||
raw: raw,
|
||||
created_at: unix_time(topic["sent_time"]),
|
||||
import_mode: true
|
||||
import_mode: true,
|
||||
}
|
||||
|
||||
unless topic_id
|
||||
msg[:title] = @htmlentities.decode(topic["subject"]).strip[0...255]
|
||||
msg[:archetype] = Archetype.private_message
|
||||
msg[:target_usernames] = usernames.join(',')
|
||||
msg[:target_usernames] = usernames.join(",")
|
||||
else
|
||||
msg[:topic_id] = topic_id
|
||||
end
|
||||
|
||||
msg
|
||||
else
|
||||
PluginStoreRow.find_or_create_by(plugin_name: "pm_import_log", key: topic["note_id"].to_s, value: "PM 'body' is empty", type_name: 'String')
|
||||
PluginStoreRow.find_or_create_by(
|
||||
plugin_name: "pm_import_log",
|
||||
key: topic["note_id"].to_s,
|
||||
value: "PM 'body' is empty",
|
||||
type_name: "String",
|
||||
)
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
def close_topics
|
||||
|
||||
puts "\nclosing closed topics..."
|
||||
|
||||
sql = "select unique_id post_id from message2 where root_id = id AND (attributes & 0x0002 ) != 0;"
|
||||
sql =
|
||||
"select unique_id post_id from message2 where root_id = id AND (attributes & 0x0002 ) != 0;"
|
||||
results = mysql_query(sql)
|
||||
|
||||
# loading post map
|
||||
existing_map = {}
|
||||
PostCustomField.where(name: 'import_unique_id').pluck(:post_id, :value).each do |post_id, import_id|
|
||||
existing_map[import_id.to_i] = post_id.to_i
|
||||
end
|
||||
PostCustomField
|
||||
.where(name: "import_unique_id")
|
||||
.pluck(:post_id, :value)
|
||||
.each { |post_id, import_id| existing_map[import_id.to_i] = post_id.to_i }
|
||||
|
||||
results.map { |r| r["post_id"] }.each_slice(500) do |ids|
|
||||
mapped = ids.map { |id| existing_map[id] }.compact
|
||||
DB.exec(<<~SQL, ids: mapped) if mapped.present?
|
||||
results
|
||||
.map { |r| r["post_id"] }
|
||||
.each_slice(500) do |ids|
|
||||
mapped = ids.map { |id| existing_map[id] }.compact
|
||||
DB.exec(<<~SQL, ids: mapped) if mapped.present?
|
||||
UPDATE topics SET closed = true
|
||||
WHERE id IN (SELECT topic_id FROM posts where id in (:ids))
|
||||
SQL
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
def create_permalinks
|
||||
@ -835,7 +878,6 @@ SQL
|
||||
|
||||
r = DB.exec sql
|
||||
puts "#{r} permalinks to posts added!"
|
||||
|
||||
end
|
||||
|
||||
def find_upload(user_id, attachment_id, real_filename)
|
||||
@ -846,7 +888,7 @@ SQL
|
||||
puts "Attachment file doesn't exist: #{filename}"
|
||||
return nil
|
||||
end
|
||||
real_filename.prepend SecureRandom.hex if real_filename[0] == '.'
|
||||
real_filename.prepend SecureRandom.hex if real_filename[0] == "."
|
||||
upload = create_upload(user_id, filename, real_filename)
|
||||
|
||||
if upload.nil? || !upload.valid?
|
||||
@ -864,48 +906,57 @@ SQL
|
||||
default_extensions = SiteSetting.authorized_extensions
|
||||
default_max_att_size = SiteSetting.max_attachment_size_kb
|
||||
SiteSetting.authorized_extensions = "*"
|
||||
SiteSetting.max_attachment_size_kb = 307200
|
||||
SiteSetting.max_attachment_size_kb = 307_200
|
||||
|
||||
current = 0
|
||||
max = Post.count
|
||||
|
||||
mysql_query("create index idxUniqueId on message2(unique_id)") rescue nil
|
||||
attachments = mysql_query("SELECT a.attachment_id, a.file_name, m.message_uid FROM tblia_attachment a INNER JOIN tblia_message_attachments m ON a.attachment_id = m.attachment_id")
|
||||
|
||||
Post.where('id > ?', @max_start_id).find_each do |post|
|
||||
begin
|
||||
id = post.custom_fields["import_unique_id"]
|
||||
next unless id
|
||||
raw = mysql_query("select body from message2 where unique_id = '#{id}'").first['body']
|
||||
unless raw
|
||||
puts "Missing raw for post: #{post.id}"
|
||||
next
|
||||
end
|
||||
new_raw = postprocess_post_raw(raw, post.user_id)
|
||||
files = attachments.select { |a| a["message_uid"].to_s == id }
|
||||
new_raw << html_for_attachments(post.user_id, files)
|
||||
unless post.raw == new_raw
|
||||
post.raw = new_raw
|
||||
post.cooked = post.cook(new_raw)
|
||||
cpp = CookedPostProcessor.new(post)
|
||||
cpp.link_post_uploads
|
||||
post.custom_fields["import_post_process"] = true
|
||||
post.save
|
||||
end
|
||||
rescue PrettyText::JavaScriptError
|
||||
puts "GOT A JS error on post: #{post.id}"
|
||||
nil
|
||||
ensure
|
||||
print_status(current += 1, max)
|
||||
end
|
||||
begin
|
||||
mysql_query("create index idxUniqueId on message2(unique_id)")
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
attachments =
|
||||
mysql_query(
|
||||
"SELECT a.attachment_id, a.file_name, m.message_uid FROM tblia_attachment a INNER JOIN tblia_message_attachments m ON a.attachment_id = m.attachment_id",
|
||||
)
|
||||
|
||||
Post
|
||||
.where("id > ?", @max_start_id)
|
||||
.find_each do |post|
|
||||
begin
|
||||
id = post.custom_fields["import_unique_id"]
|
||||
next unless id
|
||||
raw = mysql_query("select body from message2 where unique_id = '#{id}'").first["body"]
|
||||
unless raw
|
||||
puts "Missing raw for post: #{post.id}"
|
||||
next
|
||||
end
|
||||
new_raw = postprocess_post_raw(raw, post.user_id)
|
||||
files = attachments.select { |a| a["message_uid"].to_s == id }
|
||||
new_raw << html_for_attachments(post.user_id, files)
|
||||
unless post.raw == new_raw
|
||||
post.raw = new_raw
|
||||
post.cooked = post.cook(new_raw)
|
||||
cpp = CookedPostProcessor.new(post)
|
||||
cpp.link_post_uploads
|
||||
post.custom_fields["import_post_process"] = true
|
||||
post.save
|
||||
end
|
||||
rescue PrettyText::JavaScriptError
|
||||
puts "GOT A JS error on post: #{post.id}"
|
||||
nil
|
||||
ensure
|
||||
print_status(current += 1, max)
|
||||
end
|
||||
end
|
||||
|
||||
SiteSetting.authorized_extensions = default_extensions
|
||||
SiteSetting.max_attachment_size_kb = default_max_att_size
|
||||
end
|
||||
|
||||
def postprocess_post_raw(raw, user_id)
|
||||
matches = raw.match(/<messagetemplate.*<\/messagetemplate>/m) || []
|
||||
matches = raw.match(%r{<messagetemplate.*</messagetemplate>}m) || []
|
||||
matches.each do |match|
|
||||
hash = Hash.from_xml(match)
|
||||
template = hash["messagetemplate"]["zone"]["item"]
|
||||
@ -915,106 +966,123 @@ SQL
|
||||
|
||||
doc = Nokogiri::HTML5.fragment(raw)
|
||||
|
||||
doc.css("a,img,li-image").each do |l|
|
||||
upload_name, image, linked_upload = [nil] * 3
|
||||
doc
|
||||
.css("a,img,li-image")
|
||||
.each do |l|
|
||||
upload_name, image, linked_upload = [nil] * 3
|
||||
|
||||
if l.name == "li-image" && l["id"]
|
||||
upload_name = l["id"]
|
||||
else
|
||||
uri = URI.parse(l["href"] || l["src"]) rescue nil
|
||||
uri.hostname = nil if uri && uri.hostname == OLD_DOMAIN
|
||||
|
||||
if uri && !uri.hostname
|
||||
if l["href"]
|
||||
l["href"] = uri.path
|
||||
# we have an internal link, lets see if we can remap it?
|
||||
permalink = Permalink.find_by_url(uri.path) rescue nil
|
||||
|
||||
if l["href"]
|
||||
if permalink && permalink.target_url
|
||||
l["href"] = permalink.target_url
|
||||
elsif l["href"] =~ /^\/gartner\/attachments\/gartner\/([^.]*).(\w*)/
|
||||
linked_upload = "#{$1}.#{$2}"
|
||||
end
|
||||
end
|
||||
elsif l["src"]
|
||||
|
||||
# we need an upload here
|
||||
upload_name = $1 if uri.path =~ /image-id\/([^\/]+)/
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if upload_name
|
||||
png = UPLOAD_DIR + "/" + upload_name + ".png"
|
||||
jpg = UPLOAD_DIR + "/" + upload_name + ".jpg"
|
||||
gif = UPLOAD_DIR + "/" + upload_name + ".gif"
|
||||
|
||||
# check to see if we have it
|
||||
if File.exist?(png)
|
||||
image = png
|
||||
elsif File.exist?(jpg)
|
||||
image = jpg
|
||||
elsif File.exist?(gif)
|
||||
image = gif
|
||||
end
|
||||
|
||||
if image
|
||||
File.open(image) do |file|
|
||||
upload = UploadCreator.new(file, "image." + (image.ends_with?(".png") ? "png" : "jpg")).create_for(user_id)
|
||||
l.name = "img" if l.name == "li-image"
|
||||
l["src"] = upload.url
|
||||
end
|
||||
if l.name == "li-image" && l["id"]
|
||||
upload_name = l["id"]
|
||||
else
|
||||
puts "image was missing #{l["src"]}"
|
||||
uri =
|
||||
begin
|
||||
URI.parse(l["href"] || l["src"])
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
uri.hostname = nil if uri && uri.hostname == OLD_DOMAIN
|
||||
|
||||
if uri && !uri.hostname
|
||||
if l["href"]
|
||||
l["href"] = uri.path
|
||||
# we have an internal link, lets see if we can remap it?
|
||||
permalink =
|
||||
begin
|
||||
Permalink.find_by_url(uri.path)
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
|
||||
if l["href"]
|
||||
if permalink && permalink.target_url
|
||||
l["href"] = permalink.target_url
|
||||
elsif l["href"] =~ %r{^/gartner/attachments/gartner/([^.]*).(\w*)}
|
||||
linked_upload = "#{$1}.#{$2}"
|
||||
end
|
||||
end
|
||||
elsif l["src"]
|
||||
# we need an upload here
|
||||
upload_name = $1 if uri.path =~ %r{image-id/([^/]+)}
|
||||
end
|
||||
end
|
||||
end
|
||||
elsif linked_upload
|
||||
segments = linked_upload.match(/\/(\d*)\/(\d)\/([^.]*).(\w*)$/)
|
||||
|
||||
if segments.present?
|
||||
lithium_post_id = segments[1]
|
||||
attachment_number = segments[2]
|
||||
if upload_name
|
||||
png = UPLOAD_DIR + "/" + upload_name + ".png"
|
||||
jpg = UPLOAD_DIR + "/" + upload_name + ".jpg"
|
||||
gif = UPLOAD_DIR + "/" + upload_name + ".gif"
|
||||
|
||||
result = mysql_query("select a.attachment_id, f.file_name from tblia_message_attachments a
|
||||
# check to see if we have it
|
||||
if File.exist?(png)
|
||||
image = png
|
||||
elsif File.exist?(jpg)
|
||||
image = jpg
|
||||
elsif File.exist?(gif)
|
||||
image = gif
|
||||
end
|
||||
|
||||
if image
|
||||
File.open(image) do |file|
|
||||
upload =
|
||||
UploadCreator.new(
|
||||
file,
|
||||
"image." + (image.ends_with?(".png") ? "png" : "jpg"),
|
||||
).create_for(user_id)
|
||||
l.name = "img" if l.name == "li-image"
|
||||
l["src"] = upload.url
|
||||
end
|
||||
else
|
||||
puts "image was missing #{l["src"]}"
|
||||
end
|
||||
elsif linked_upload
|
||||
segments = linked_upload.match(%r{/(\d*)/(\d)/([^.]*).(\w*)$})
|
||||
|
||||
if segments.present?
|
||||
lithium_post_id = segments[1]
|
||||
attachment_number = segments[2]
|
||||
|
||||
result =
|
||||
mysql_query(
|
||||
"select a.attachment_id, f.file_name from tblia_message_attachments a
|
||||
INNER JOIN message2 m ON a.message_uid = m.unique_id
|
||||
INNER JOIN tblia_attachment f ON a.attachment_id = f.attachment_id
|
||||
where m.id = #{lithium_post_id} AND a.attach_num = #{attachment_number} limit 0, 1")
|
||||
where m.id = #{lithium_post_id} AND a.attach_num = #{attachment_number} limit 0, 1",
|
||||
)
|
||||
|
||||
result.each do |row|
|
||||
upload, filename = find_upload(user_id, row["attachment_id"], row["file_name"])
|
||||
if upload.present?
|
||||
l["href"] = upload.url
|
||||
else
|
||||
puts "attachment was missing #{l["href"]}"
|
||||
result.each do |row|
|
||||
upload, filename = find_upload(user_id, row["attachment_id"], row["file_name"])
|
||||
if upload.present?
|
||||
l["href"] = upload.url
|
||||
else
|
||||
puts "attachment was missing #{l["href"]}"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
# for user mentions
|
||||
doc.css("li-user").each do |l|
|
||||
uid = l["uid"]
|
||||
doc
|
||||
.css("li-user")
|
||||
.each do |l|
|
||||
uid = l["uid"]
|
||||
|
||||
if uid.present?
|
||||
user = UserCustomField.find_by(name: 'import_id', value: uid).try(:user)
|
||||
if user.present?
|
||||
username = user.username
|
||||
span = l.document.create_element "span"
|
||||
span.inner_html = "@#{username}"
|
||||
l.replace span
|
||||
if uid.present?
|
||||
user = UserCustomField.find_by(name: "import_id", value: uid).try(:user)
|
||||
if user.present?
|
||||
username = user.username
|
||||
span = l.document.create_element "span"
|
||||
span.inner_html = "@#{username}"
|
||||
l.replace span
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
raw = ReverseMarkdown.convert(doc.to_s)
|
||||
raw.gsub!(/^\s* \s*$/, "")
|
||||
# ugly quotes
|
||||
raw.gsub!(/^>[\s\*]*$/, "")
|
||||
raw.gsub!(/:([a-z]+):/) do |match|
|
||||
":#{SMILEY_SUBS[$1] || $1}:"
|
||||
end
|
||||
raw.gsub!(/:([a-z]+):/) { |match| ":#{SMILEY_SUBS[$1] || $1}:" }
|
||||
# nbsp central
|
||||
raw.gsub!(/([a-zA-Z0-9]) ([a-zA-Z0-9])/, "\\1 \\2")
|
||||
raw
|
||||
@ -1037,7 +1105,6 @@ SQL
|
||||
def mysql_query(sql)
|
||||
@client.query(sql, cache_rows: true)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
ImportScripts::Lithium.new.perform
|
||||
|
Reference in New Issue
Block a user