You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

610 lines
26 KiB

  1. # frozen_string_literal: true
  2. require 'tty-prompt'
  3. require_relative '../../config/boot'
  4. require_relative '../../config/environment'
  5. require_relative 'cli_helper'
  6. module Mastodon
  7. class MaintenanceCLI < Thor
  8. include CLIHelper
  9. def self.exit_on_failure?
  10. true
  11. end
  12. MIN_SUPPORTED_VERSION = 2019_10_01_213028
  13. MAX_SUPPORTED_VERSION = 2020_10_17_234926
  14. # Stubs to enjoy ActiveRecord queries while not depending on a particular
  15. # version of the code/database
  16. class Status < ApplicationRecord; end
  17. class StatusPin < ApplicationRecord; end
  18. class Poll < ApplicationRecord; end
  19. class Report < ApplicationRecord; end
  20. class Tombstone < ApplicationRecord; end
  21. class Favourite < ApplicationRecord; end
  22. class Follow < ApplicationRecord; end
  23. class FollowRequest < ApplicationRecord; end
  24. class Block < ApplicationRecord; end
  25. class Mute < ApplicationRecord; end
  26. class AccountIdentityProof < ApplicationRecord; end
  27. class AccountModerationNote < ApplicationRecord; end
  28. class AccountPin < ApplicationRecord; end
  29. class ListAccount < ApplicationRecord; end
  30. class PollVote < ApplicationRecord; end
  31. class Mention < ApplicationRecord; end
  32. class AccountDomainBlock < ApplicationRecord; end
  33. class AnnouncementReaction < ApplicationRecord; end
  34. class FeaturedTag < ApplicationRecord; end
  35. class CustomEmoji < ApplicationRecord; end
  36. class CustomEmojiCategory < ApplicationRecord; end
  37. class Bookmark < ApplicationRecord; end
  38. class WebauthnCredential < ApplicationRecord; end
  39. class PreviewCard < ApplicationRecord
  40. self.inheritance_column = false
  41. end
  42. class MediaAttachment < ApplicationRecord
  43. self.inheritance_column = nil
  44. end
  45. class AccountStat < ApplicationRecord
  46. belongs_to :account, inverse_of: :account_stat
  47. end
  48. class Account < ApplicationRecord
  49. # Dummy class, to make migration possible across version changes
  50. has_one :user, inverse_of: :account
  51. has_one :account_stat, inverse_of: :account
  52. scope :local, -> { where(domain: nil) }
  53. def local?
  54. domain.nil?
  55. end
  56. def acct
  57. local? ? username : "#{username}@#{domain}"
  58. end
  59. end
  60. class User < ApplicationRecord
  61. belongs_to :account, inverse_of: :user
  62. end
  63. desc 'fix-duplicates', 'Fix duplicates in database and rebuild indexes'
  64. long_desc <<~LONG_DESC
  65. Delete or merge duplicate accounts, statuses, emojis, etc. and rebuild indexes.
  66. This is useful if your database indexes are corrupted because of issues such as https://wiki.postgresql.org/wiki/Locale_data_changes
  67. Mastodon has to be stopped to run this task, which will take a long time and may be destructive.
  68. LONG_DESC
  69. def fix_duplicates
  70. @prompt = TTY::Prompt.new
  71. if ActiveRecord::Migrator.current_version < MIN_SUPPORTED_VERSION
  72. @prompt.warn 'Your version of the database schema is too old and is not supported by this script.'
  73. @prompt.warn 'Please update to at least Mastodon 3.0.0 before running this script.'
  74. exit(1)
  75. elsif ActiveRecord::Migrator.current_version > MAX_SUPPORTED_VERSION
  76. @prompt.warn 'Your version of the database schema is more recent than this script, this may cause unexpected errors.'
  77. exit(1) unless @prompt.yes?('Continue anyway?')
  78. end
  79. @prompt.warn 'This task will take a long time to run and is potentially destructive.'
  80. @prompt.warn 'Please make sure to stop Mastodon and have a backup.'
  81. exit(1) unless @prompt.yes?('Continue?')
  82. deduplicate_accounts!
  83. deduplicate_users!
  84. deduplicate_account_domain_blocks!
  85. deduplicate_account_identity_proofs!
  86. deduplicate_announcement_reactions!
  87. deduplicate_conversations!
  88. deduplicate_custom_emojis!
  89. deduplicate_custom_emoji_categories!
  90. deduplicate_domain_allows!
  91. deduplicate_domain_blocks!
  92. deduplicate_unavailable_domains!
  93. deduplicate_email_domain_blocks!
  94. deduplicate_media_attachments!
  95. deduplicate_preview_cards!
  96. deduplicate_statuses!
  97. deduplicate_tags!
  98. deduplicate_webauthn_credentials!
  99. Rails.cache.clear
  100. @prompt.say 'Finished!'
  101. end
  102. private
  103. def deduplicate_accounts!
  104. remove_index_if_exists!(:accounts, 'index_accounts_on_username_and_domain_lower')
  105. @prompt.say 'Deduplicating accounts… for local accounts, you will be asked to chose which account to keep unchanged.'
  106. find_duplicate_accounts.each do |row|
  107. accounts = Account.where(id: row['ids'].split(',')).to_a
  108. if accounts.first.local?
  109. deduplicate_local_accounts!(accounts)
  110. else
  111. deduplicate_remote_accounts!(accounts)
  112. end
  113. end
  114. @prompt.say 'Restoring index_accounts_on_username_and_domain_lower…'
  115. if ActiveRecord::Migrator.current_version < 20200620164023
  116. ActiveRecord::Base.connection.add_index :accounts, 'lower (username), lower(domain)', name: 'index_accounts_on_username_and_domain_lower', unique: true
  117. else
  118. ActiveRecord::Base.connection.add_index :accounts, "lower (username), COALESCE(lower(domain), '')", name: 'index_accounts_on_username_and_domain_lower', unique: true
  119. end
  120. end
  121. def deduplicate_users!
  122. remove_index_if_exists!(:users, 'index_users_on_confirmation_token')
  123. remove_index_if_exists!(:users, 'index_users_on_email')
  124. remove_index_if_exists!(:users, 'index_users_on_remember_token')
  125. remove_index_if_exists!(:users, 'index_users_on_reset_password_token')
  126. @prompt.say 'Deduplicating user records…'
  127. # Deduplicating email
  128. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users GROUP BY email HAVING count(*) > 1").each do |row|
  129. users = User.where(id: row['ids'].split(',')).sort_by(&:updated_at).reverse
  130. ref_user = users.shift
  131. @prompt.warn "Multiple users registered with e-mail address #{ref_user.email}."
  132. @prompt.warn "e-mail will be disabled for the following accounts: #{user.map(&:account).map(&:acct).join(', ')}"
  133. @prompt.warn 'Please reach out to them and set another address with `tootctl account modify` or delete them.'
  134. i = 0
  135. users.each do |user|
  136. user.update!(email: "#{i} " + user.email)
  137. end
  138. end
  139. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users WHERE confirmation_token IS NOT NULL GROUP BY confirmation_token HAVING count(*) > 1").each do |row|
  140. users = User.where(id: row['ids'].split(',')).sort_by(&:created_at).reverse.drop(1)
  141. @prompt.warn "Unsetting confirmation token for those accounts: #{users.map(&:account).map(&:acct).join(', ')}"
  142. users.each do |user|
  143. user.update!(confirmation_token: nil)
  144. end
  145. end
  146. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users WHERE remember_token IS NOT NULL GROUP BY remember_token HAVING count(*) > 1").each do |row|
  147. users = User.where(id: row['ids'].split(',')).sort_by(&:updated_at).reverse.drop(1)
  148. @prompt.warn "Unsetting remember token for those accounts: #{users.map(&:account).map(&:acct).join(', ')}"
  149. users.each do |user|
  150. user.update!(remember_token: nil)
  151. end
  152. end
  153. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users WHERE reset_password_token IS NOT NULL GROUP BY reset_password_token HAVING count(*) > 1").each do |row|
  154. users = User.where(id: row['ids'].split(',')).sort_by(&:updated_at).reverse.drop(1)
  155. @prompt.warn "Unsetting password reset token for those accounts: #{users.map(&:account).map(&:acct).join(', ')}"
  156. users.each do |user|
  157. user.update!(reset_password_token: nil)
  158. end
  159. end
  160. @prompt.say 'Restoring users indexes…'
  161. ActiveRecord::Base.connection.add_index :users, ['confirmation_token'], name: 'index_users_on_confirmation_token', unique: true
  162. ActiveRecord::Base.connection.add_index :users, ['email'], name: 'index_users_on_email', unique: true
  163. ActiveRecord::Base.connection.add_index :users, ['remember_token'], name: 'index_users_on_remember_token', unique: true
  164. ActiveRecord::Base.connection.add_index :users, ['reset_password_token'], name: 'index_users_on_reset_password_token', unique: true
  165. end
  166. def deduplicate_account_domain_blocks!
  167. remove_index_if_exists!(:account_domain_blocks, 'index_account_domain_blocks_on_account_id_and_domain')
  168. @prompt.say 'Removing duplicate account domain blocks…'
  169. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM account_domain_blocks GROUP BY account_id, domain HAVING count(*) > 1").each do |row|
  170. AccountDomainBlock.where(id: row['ids'].split(',').drop(1)).delete_all
  171. end
  172. @prompt.say 'Restoring account domain blocks indexes…'
  173. ActiveRecord::Base.connection.add_index :account_domain_blocks, ['account_id', 'domain'], name: 'index_account_domain_blocks_on_account_id_and_domain', unique: true
  174. end
  175. def deduplicate_account_identity_proofs!
  176. remove_index_if_exists!(:account_identity_proofs, 'index_account_proofs_on_account_and_provider_and_username')
  177. @prompt.say 'Removing duplicate account identity proofs…'
  178. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM account_identity_proofs GROUP BY account_id, provider, provider_username HAVING count(*) > 1").each do |row|
  179. AccountIdentityProof.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  180. end
  181. @prompt.say 'Restoring account identity proofs indexes…'
  182. ActiveRecord::Base.connection.add_index :account_identity_proofs, ['account_id', 'provider', 'provider_username'], name: 'index_account_proofs_on_account_and_provider_and_username', unique: true
  183. end
  184. def deduplicate_announcement_reactions!
  185. return unless ActiveRecord::Base.connection.table_exists?(:announcement_reactions)
  186. remove_index_if_exists!(:announcement_reactions, 'index_announcement_reactions_on_account_id_and_announcement_id')
  187. @prompt.say 'Removing duplicate account identity proofs…'
  188. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM announcement_reactions GROUP BY account_id, announcement_id, name HAVING count(*) > 1").each do |row|
  189. AnnouncementReaction.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  190. end
  191. @prompt.say 'Restoring announcement_reactions indexes…'
  192. ActiveRecord::Base.connection.add_index :announcement_reactions, ['account_id', 'announcement_id', 'name'], name: 'index_announcement_reactions_on_account_id_and_announcement_id', unique: true
  193. end
  194. def deduplicate_conversations!
  195. remove_index_if_exists!(:conversations, 'index_conversations_on_uri')
  196. @prompt.say 'Deduplicating conversations…'
  197. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM conversations WHERE uri IS NOT NULL GROUP BY uri HAVING count(*) > 1").each do |row|
  198. conversations = Conversation.where(id: row['ids'].split(',')).sort_by(&:id).reverse
  199. ref_conversation = conversations.shift
  200. conversations.each do |other|
  201. merge_conversations!(ref_conversation, other)
  202. other.destroy
  203. end
  204. end
  205. @prompt.say 'Restoring conversations indexes…'
  206. ActiveRecord::Base.connection.add_index :conversations, ['uri'], name: 'index_conversations_on_uri', unique: true
  207. end
  208. def deduplicate_custom_emojis!
  209. remove_index_if_exists!(:custom_emojis, 'index_custom_emojis_on_shortcode_and_domain')
  210. @prompt.say 'Deduplicating custom_emojis…'
  211. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM custom_emojis GROUP BY shortcode, domain HAVING count(*) > 1").each do |row|
  212. emojis = CustomEmoji.where(id: row['ids'].split(',')).sort_by(&:id).reverse
  213. ref_emoji = emojis.shift
  214. emojis.each do |other|
  215. merge_custom_emojis!(ref_emoji, other)
  216. other.destroy
  217. end
  218. end
  219. @prompt.say 'Restoring custom_emojis indexes…'
  220. ActiveRecord::Base.connection.add_index :custom_emojis, ['shortcode', 'domain'], name: 'index_custom_emojis_on_shortcode_and_domain', unique: true
  221. end
  222. def deduplicate_custom_emoji_categories!
  223. remove_index_if_exists!(:custom_emoji_categories, 'index_custom_emoji_categories_on_name')
  224. @prompt.say 'Deduplicating custom_emoji_categories…'
  225. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM custom_emoji_categories GROUP BY name HAVING count(*) > 1").each do |row|
  226. categories = CustomEmojiCategory.where(id: row['ids'].split(',')).sort_by(&:id).reverse
  227. ref_category = categories.shift
  228. categories.each do |other|
  229. merge_custom_emoji_categories!(ref_category, other)
  230. other.destroy
  231. end
  232. end
  233. @prompt.say 'Restoring custom_emoji_categories indexes…'
  234. ActiveRecord::Base.connection.add_index :custom_emoji_categories, ['name'], name: 'index_custom_emoji_categories_on_name', unique: true
  235. end
  236. def deduplicate_domain_allows!
  237. remove_index_if_exists!(:domain_allows, 'index_domain_allows_on_domain')
  238. @prompt.say 'Deduplicating domain_allows…'
  239. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM domain_allows GROUP BY domain HAVING count(*) > 1").each do |row|
  240. DomainAllow.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  241. end
  242. @prompt.say 'Restoring domain_allows indexes…'
  243. ActiveRecord::Base.connection.add_index :domain_allows, ['domain'], name: 'index_domain_allows_on_domain', unique: true
  244. end
  245. def deduplicate_domain_blocks!
  246. remove_index_if_exists!(:domain_blocks, 'index_domain_blocks_on_domain')
  247. @prompt.say 'Deduplicating domain_allows…'
  248. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM domain_blocks GROUP BY domain HAVING count(*) > 1").each do |row|
  249. domain_blocks = DomainBlock.where(id: row['ids'].split(',')).by_severity.reverse.to_a
  250. reject_media = domain_blocks.any?(&:reject_media?)
  251. reject_reports = domain_blocks.any?(&:reject_reports?)
  252. reference_block = domain_blocks.shift
  253. private_comment = domain_blocks.reduce(reference_block.private_comment.presence) { |a, b| a || b.private_comment.presence }
  254. public_comment = domain_blocks.reduce(reference_block.public_comment.presence) { |a, b| a || b.public_comment.presence }
  255. reference_block.update!(reject_media: reject_media, reject_reports: reject_reports, private_comment: private_comment, public_comment: public_comment)
  256. domain_blocks.each(&:destroy)
  257. end
  258. @prompt.say 'Restoring domain_blocks indexes…'
  259. ActiveRecord::Base.connection.add_index :domain_blocks, ['domain'], name: 'index_domain_blocks_on_domain', unique: true
  260. end
  261. def deduplicate_unavailable_domains!
  262. return unless ActiveRecord::Base.connection.table_exists?(:unavailable_domains)
  263. remove_index_if_exists!(:unavailable_domains, 'index_unavailable_domains_on_domain')
  264. @prompt.say 'Deduplicating unavailable_domains…'
  265. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM unavailable_domains GROUP BY domain HAVING count(*) > 1").each do |row|
  266. UnavailableDomain.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  267. end
  268. @prompt.say 'Restoring domain_allows indexes…'
  269. ActiveRecord::Base.connection.add_index :unavailable_domains, ['domain'], name: 'index_unavailable_domains_on_domain', unique: true
  270. end
  271. def deduplicate_email_domain_blocks!
  272. remove_index_if_exists!(:email_domain_blocks, 'index_email_domain_blocks_on_domain')
  273. @prompt.say 'Deduplicating email_domain_blocks…'
  274. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM email_domain_blocks GROUP BY domain HAVING count(*) > 1").each do |row|
  275. domain_blocks = EmailDomainBlock.where(id: row['ids'].split(',')).sort_by { |b| b.parent.nil? ? 1 : 0 }.to_a
  276. domain_blocks.drop(1).each(&:destroy)
  277. end
  278. @prompt.say 'Restoring email_domain_blocks indexes…'
  279. ActiveRecord::Base.connection.add_index :email_domain_blocks, ['domain'], name: 'index_email_domain_blocks_on_domain', unique: true
  280. end
  281. def deduplicate_media_attachments!
  282. remove_index_if_exists!(:media_attachments, 'index_media_attachments_on_shortcode')
  283. @prompt.say 'Deduplicating media_attachments…'
  284. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM media_attachments WHERE shortcode IS NOT NULL GROUP BY shortcode HAVING count(*) > 1").each do |row|
  285. MediaAttachment.where(id: row['ids'].split(',').drop(1)).update_all(shortcode: nil)
  286. end
  287. @prompt.say 'Restoring media_attachments indexes…'
  288. ActiveRecord::Base.connection.add_index :media_attachments, ['shortcode'], name: 'index_media_attachments_on_shortcode', unique: true
  289. end
  290. def deduplicate_preview_cards!
  291. remove_index_if_exists!(:preview_cards, 'index_preview_cards_on_url')
  292. @prompt.say 'Deduplicating preview_cards…'
  293. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM preview_cards GROUP BY url HAVING count(*) > 1").each do |row|
  294. PreviewCard.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  295. end
  296. @prompt.say 'Restoring preview_cards indexes…'
  297. ActiveRecord::Base.connection.add_index :preview_cards, ['url'], name: 'index_preview_cards_on_url', unique: true
  298. end
  299. def deduplicate_statuses!
  300. remove_index_if_exists!(:statuses, 'index_statuses_on_uri')
  301. @prompt.say 'Deduplicating statuses…'
  302. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM statuses WHERE uri IS NOT NULL GROUP BY uri HAVING count(*) > 1").each do |row|
  303. statuses = Status.where(id: row['ids'].split(',')).sort_by(&:id)
  304. ref_status = statuses.shift
  305. statuses.each do |status|
  306. merge_statuses!(ref_status, status) if status.account_id == ref_status.account_id
  307. status.destroy
  308. end
  309. end
  310. @prompt.say 'Restoring statuses indexes…'
  311. ActiveRecord::Base.connection.add_index :statuses, ['uri'], name: 'index_statuses_on_uri', unique: true
  312. end
  313. def deduplicate_tags!
  314. remove_index_if_exists!(:tags, 'index_tags_on_name_lower')
  315. @prompt.say 'Deduplicating tags…'
  316. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM tags GROUP BY lower((name)::text) HAVING count(*) > 1").each do |row|
  317. tags = Tag.where(id: row['ids'].split(',')).sort_by { |t| [t.usable?, t.trendable?, t.listable?].count(false) }
  318. ref_tag = tags.shift
  319. tags.each do |tag|
  320. merge_tags!(ref_tag, tag)
  321. tag.destroy
  322. end
  323. end
  324. @prompt.say 'Restoring tags indexes…'
  325. ActiveRecord::Base.connection.add_index :tags, 'lower((name)::text)', name: 'index_tags_on_name_lower', unique: true
  326. end
  327. def deduplicate_webauthn_credentials!
  328. return unless ActiveRecord::Base.connection.table_exists?(:webauthn_credentials)
  329. remove_index_if_exists!(:webauthn_credentials, 'index_webauthn_credentials_on_external_id')
  330. @prompt.say 'Deduplicating webauthn_credentials…'
  331. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM webauthn_credentials GROUP BY external_id HAVING count(*) > 1").each do |row|
  332. WebauthnCredential.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  333. end
  334. @prompt.say 'Restoring webauthn_credentials indexes…'
  335. ActiveRecord::Base.connection.add_index :webauthn_credentials, ['external_id'], name: 'index_webauthn_credentials_on_external_id', unique: true
  336. end
  337. def deduplicate_local_accounts!(accounts)
  338. accounts = accounts.sort_by(&:id).reverse
  339. @prompt.warn "Multiple local accounts were found for username '#{accounts.first.username}'."
  340. @prompt.warn 'All those accounts are distinct accounts but only the most recently-created one is fully-functionnal.'
  341. accounts.each_with_index do |account, idx|
  342. @prompt.say '%2d. %s: created at: %s; updated at: %s; last logged in at: %s; statuses: %5d; last status at: %s' % [idx, account.username, account.created_at, account.updated_at, account.user&.last_sign_in_at&.to_s || 'N/A', account.account_stat&.statuses_count || 0, account.account_stat&.last_status_at || 'N/A']
  343. end
  344. @prompt.say 'Please chose the one to keep unchanged, other ones will be automatically renamed.'
  345. ref_id = @prompt.ask('Account to keep unchanged:') do |q|
  346. q.required true
  347. q.default 0
  348. q.convert :int
  349. end
  350. accounts.delete_at(ref_id)
  351. i = 0
  352. accounts.each do |account|
  353. i += 1
  354. username = account.username + "_#{i}"
  355. while Account.local.exists?(username: username)
  356. i += 1
  357. username = account.username + "_#{i}"
  358. end
  359. account.update!(username: username)
  360. end
  361. end
  362. def deduplicate_remote_accounts!(accounts)
  363. accounts = accounts.sort_by(&:updated_at).reverse
  364. reference_account = accounts.shift
  365. accounts.each do |other_account|
  366. if other_account.public_key == reference_account.public_key
  367. # The accounts definitely point to the same resource, so
  368. # it's safe to re-attribute content and relationships
  369. merge_accounts!(reference_account, other_account)
  370. end
  371. other_account.destroy
  372. end
  373. end
  374. def merge_accounts!(main_account, duplicate_account)
  375. # Since it's the same remote resource, the remote resource likely
  376. # already believes we are following/blocking, so it's safe to
  377. # re-attribute the relationships too. However, during the presence
  378. # of the index bug users could have *also* followed the reference
  379. # account already, therefore mass update will not work and we need
  380. # to check for (and skip past) uniqueness errors
  381. owned_classes = [
  382. Status, StatusPin, MediaAttachment, Poll, Report, Tombstone, Favourite,
  383. Follow, FollowRequest, Block, Mute, AccountIdentityProof,
  384. AccountModerationNote, AccountPin, AccountStat, ListAccount,
  385. PollVote, Mention
  386. ]
  387. owned_classes.each do |klass|
  388. klass.where(account_id: duplicate_account.id).find_each do |record|
  389. begin
  390. record.update_attribute(:account_id, main_account.id)
  391. rescue ActiveRecord::RecordNotUnique
  392. next
  393. end
  394. end
  395. end
  396. target_classes = [Follow, FollowRequest, Block, Mute, AccountModerationNote, AccountPin]
  397. target_classes.each do |klass|
  398. klass.where(target_account_id: duplicate_account.id).find_each do |record|
  399. begin
  400. record.update_attribute(:target_account_id, main_account.id)
  401. rescue ActiveRecord::RecordNotUnique
  402. next
  403. end
  404. end
  405. end
  406. end
  407. def merge_conversations!(main_conv, duplicate_conv)
  408. owned_classes = [ConversationMute, AccountConversation]
  409. owned_classes.each do |klass|
  410. klass.where(conversation_id: duplicate_conv.id).find_each do |record|
  411. begin
  412. record.update_attribute(:account_id, main_conv.id)
  413. rescue ActiveRecord::RecordNotUnique
  414. next
  415. end
  416. end
  417. end
  418. end
  419. def merge_custom_emojis!(main_emoji, duplicate_emoji)
  420. owned_classes = [AnnouncementReaction]
  421. owned_classes.each do |klass|
  422. klass.where(custom_emoji_id: duplicate_emoji.id).update_all(custom_emoji_id: main_emoji.id)
  423. end
  424. end
  425. def merge_custom_emoji_categories!(main_category, duplicate_category)
  426. owned_classes = [CustomEmoji]
  427. owned_classes.each do |klass|
  428. klass.where(category_id: duplicate_category.id).update_all(category_id: main_category.id)
  429. end
  430. end
  431. def merge_statuses!(main_status, duplicate_status)
  432. owned_classes = [Favourite, Mention, Poll]
  433. owned_classes << Bookmark if ActiveRecord::Base.connection.table_exists?(:bookmarks)
  434. owned_classes.each do |klass|
  435. klass.where(status_id: duplicate_status.id).find_each do |record|
  436. begin
  437. record.update_attribute(:status_id, main_status.id)
  438. rescue ActiveRecord::RecordNotUnique
  439. next
  440. end
  441. end
  442. end
  443. StatusPin.where(account_id: main_status.account_id, status_id: duplicate_status.id).find_each do |record|
  444. begin
  445. record.update_attribute(:status_id, main_status.id)
  446. rescue ActiveRecord::RecordNotUnique
  447. next
  448. end
  449. end
  450. Status.where(in_reply_to_id: duplicate_status.id).find_each do |record|
  451. begin
  452. record.update_attribute(:in_reply_to_id, main_status.id)
  453. rescue ActiveRecord::RecordNotUnique
  454. next
  455. end
  456. end
  457. Status.where(reblog_of_id: duplicate_status.id).find_each do |record|
  458. begin
  459. record.update_attribute(:reblog_of_id, main_status.id)
  460. rescue ActiveRecord::RecordNotUnique
  461. next
  462. end
  463. end
  464. end
  465. def merge_tags!(main_tag, duplicate_tag)
  466. [FeaturedTag].each do |klass|
  467. klass.where(tag_id: duplicate_tag.id).find_each do |record|
  468. begin
  469. record.update_attribute(:tag_id, main_tag.id)
  470. rescue ActiveRecord::RecordNotUnique
  471. next
  472. end
  473. end
  474. end
  475. end
  476. def find_duplicate_accounts
  477. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM accounts GROUP BY lower(username), COALESCE(lower(domain), '') HAVING count(*) > 1")
  478. end
  479. def remove_index_if_exists!(table, name)
  480. ActiveRecord::Base.connection.remove_index(table, name: name)
  481. rescue ArgumentError
  482. nil
  483. rescue ActiveRecord::StatementInvalid
  484. nil
  485. end
  486. end
  487. end