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.

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