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.

803 lines
32 KiB

  1. # frozen_string_literal: true
  2. require 'optparse'
  3. require 'colorize'
  4. namespace :mastodon do
  5. desc 'Configure the instance for production use'
  6. task :setup do
  7. prompt = TTY::Prompt.new
  8. env = {}
  9. begin
  10. prompt.say('Your instance is identified by its domain name. Changing it afterward will break things.')
  11. env['LOCAL_DOMAIN'] = prompt.ask('Domain name:') do |q|
  12. q.required true
  13. q.modify :strip
  14. q.validate(/\A[a-z0-9\.\-]+\z/i)
  15. q.messages[:valid?] = 'Invalid domain. If you intend to use unicode characters, enter punycode here'
  16. end
  17. prompt.say "\n"
  18. prompt.say('Single user mode disables registrations and redirects the landing page to your public profile.')
  19. env['SINGLE_USER_MODE'] = prompt.yes?('Do you want to enable single user mode?', default: false)
  20. %w(SECRET_KEY_BASE OTP_SECRET).each do |key|
  21. env[key] = SecureRandom.hex(64)
  22. end
  23. vapid_key = Webpush.generate_key
  24. env['VAPID_PRIVATE_KEY'] = vapid_key.private_key
  25. env['VAPID_PUBLIC_KEY'] = vapid_key.public_key
  26. prompt.say "\n"
  27. using_docker = prompt.yes?('Are you using Docker to run Mastodon?')
  28. db_connection_works = false
  29. prompt.say "\n"
  30. loop do
  31. env['DB_HOST'] = prompt.ask('PostgreSQL host:') do |q|
  32. q.required true
  33. q.default using_docker ? 'db' : '/var/run/postgresql'
  34. q.modify :strip
  35. end
  36. env['DB_PORT'] = prompt.ask('PostgreSQL port:') do |q|
  37. q.required true
  38. q.default 5432
  39. q.convert :int
  40. end
  41. env['DB_NAME'] = prompt.ask('Name of PostgreSQL database:') do |q|
  42. q.required true
  43. q.default using_docker ? 'postgres' : 'mastodon_production'
  44. q.modify :strip
  45. end
  46. env['DB_USER'] = prompt.ask('Name of PostgreSQL user:') do |q|
  47. q.required true
  48. q.default using_docker ? 'postgres' : 'mastodon'
  49. q.modify :strip
  50. end
  51. env['DB_PASS'] = prompt.ask('Password of PostgreSQL user:') do |q|
  52. q.echo false
  53. end
  54. # The chosen database may not exist yet. Connect to default database
  55. # to avoid "database does not exist" error.
  56. db_options = {
  57. adapter: :postgresql,
  58. database: 'postgres',
  59. host: env['DB_HOST'],
  60. port: env['DB_PORT'],
  61. user: env['DB_USER'],
  62. password: env['DB_PASS'],
  63. }
  64. begin
  65. ActiveRecord::Base.establish_connection(db_options)
  66. ActiveRecord::Base.connection
  67. prompt.ok 'Database configuration works! 🎆'
  68. db_connection_works = true
  69. break
  70. rescue StandardError => e
  71. prompt.error 'Database connection could not be established with this configuration, try again.'
  72. prompt.error e.message
  73. break unless prompt.yes?('Try again?')
  74. end
  75. end
  76. prompt.say "\n"
  77. loop do
  78. env['REDIS_HOST'] = prompt.ask('Redis host:') do |q|
  79. q.required true
  80. q.default using_docker ? 'redis' : 'localhost'
  81. q.modify :strip
  82. end
  83. env['REDIS_PORT'] = prompt.ask('Redis port:') do |q|
  84. q.required true
  85. q.default 6379
  86. q.convert :int
  87. end
  88. redis_options = {
  89. host: env['REDIS_HOST'],
  90. port: env['REDIS_PORT'],
  91. driver: :hiredis,
  92. }
  93. begin
  94. redis = Redis.new(redis_options)
  95. redis.ping
  96. prompt.ok 'Redis configuration works! 🎆'
  97. break
  98. rescue StandardError => e
  99. prompt.error 'Redis connection could not be established with this configuration, try again.'
  100. prompt.error e.message
  101. break unless prompt.yes?('Try again?')
  102. end
  103. end
  104. prompt.say "\n"
  105. if prompt.yes?('Do you want to store uploaded files on the cloud?', default: false)
  106. case prompt.select('Provider', ['Amazon S3', 'Wasabi', 'Minio'])
  107. when 'Amazon S3'
  108. env['S3_ENABLED'] = 'true'
  109. env['S3_PROTOCOL'] = 'https'
  110. env['S3_BUCKET'] = prompt.ask('S3 bucket name:') do |q|
  111. q.required true
  112. q.default "files.#{env['LOCAL_DOMAIN']}"
  113. q.modify :strip
  114. end
  115. env['S3_REGION'] = prompt.ask('S3 region:') do |q|
  116. q.required true
  117. q.default 'us-east-1'
  118. q.modify :strip
  119. end
  120. env['S3_HOSTNAME'] = prompt.ask('S3 hostname:') do |q|
  121. q.required true
  122. q.default 's3-us-east-1.amazonaws.com'
  123. q.modify :strip
  124. end
  125. env['AWS_ACCESS_KEY_ID'] = prompt.ask('S3 access key:') do |q|
  126. q.required true
  127. q.modify :strip
  128. end
  129. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('S3 secret key:') do |q|
  130. q.required true
  131. q.modify :strip
  132. end
  133. when 'Wasabi'
  134. env['S3_ENABLED'] = 'true'
  135. env['S3_PROTOCOL'] = 'https'
  136. env['S3_REGION'] = 'us-east-1'
  137. env['S3_HOSTNAME'] = 's3.wasabisys.com'
  138. env['S3_ENDPOINT'] = 'https://s3.wasabisys.com/'
  139. env['S3_BUCKET'] = prompt.ask('Wasabi bucket name:') do |q|
  140. q.required true
  141. q.default "files.#{env['LOCAL_DOMAIN']}"
  142. q.modify :strip
  143. end
  144. env['AWS_ACCESS_KEY_ID'] = prompt.ask('Wasabi access key:') do |q|
  145. q.required true
  146. q.modify :strip
  147. end
  148. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('Wasabi secret key:') do |q|
  149. q.required true
  150. q.modify :strip
  151. end
  152. when 'Minio'
  153. env['S3_ENABLED'] = 'true'
  154. env['S3_PROTOCOL'] = 'https'
  155. env['S3_REGION'] = 'us-east-1'
  156. env['S3_ENDPOINT'] = prompt.ask('Minio endpoint URL:') do |q|
  157. q.required true
  158. q.modify :strip
  159. end
  160. env['S3_PROTOCOL'] = env['S3_ENDPOINT'].start_with?('https') ? 'https' : 'http'
  161. env['S3_HOSTNAME'] = env['S3_ENDPOINT'].gsub(/\Ahttps?:\/\//, '')
  162. env['S3_BUCKET'] = prompt.ask('Minio bucket name:') do |q|
  163. q.required true
  164. q.default "files.#{env['LOCAL_DOMAIN']}"
  165. q.modify :strip
  166. end
  167. env['AWS_ACCESS_KEY_ID'] = prompt.ask('Minio access key:') do |q|
  168. q.required true
  169. q.modify :strip
  170. end
  171. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('Minio secret key:') do |q|
  172. q.required true
  173. q.modify :strip
  174. end
  175. end
  176. if prompt.yes?('Do you want to access the uploaded files from your own domain?')
  177. env['S3_CLOUDFRONT_HOST'] = prompt.ask('Domain for uploaded files:') do |q|
  178. q.required true
  179. q.default "files.#{env['LOCAL_DOMAIN']}"
  180. q.modify :strip
  181. end
  182. end
  183. end
  184. prompt.say "\n"
  185. loop do
  186. env['SMTP_SERVER'] = prompt.ask('SMTP server:') do |q|
  187. q.required true
  188. q.default 'smtp.mailgun.org'
  189. q.modify :strip
  190. end
  191. env['SMTP_PORT'] = prompt.ask('SMTP port:') do |q|
  192. q.required true
  193. q.default 587
  194. q.convert :int
  195. end
  196. env['SMTP_LOGIN'] = prompt.ask('SMTP username:') do |q|
  197. q.modify :strip
  198. end
  199. env['SMTP_PASSWORD'] = prompt.ask('SMTP password:') do |q|
  200. q.echo false
  201. end
  202. env['SMTP_FROM_ADDRESS'] = prompt.ask('E-mail address to send e-mails "from":') do |q|
  203. q.required true
  204. q.default "Mastodon <notifications@#{env['LOCAL_DOMAIN']}>"
  205. q.modify :strip
  206. end
  207. break unless prompt.yes?('Send a test e-mail with this configuration right now?')
  208. send_to = prompt.ask('Send test e-mail to:', required: true)
  209. begin
  210. ActionMailer::Base.smtp_settings = {
  211. :port => env['SMTP_PORT'],
  212. :address => env['SMTP_SERVER'],
  213. :user_name => env['SMTP_LOGIN'].presence,
  214. :password => env['SMTP_PASSWORD'].presence,
  215. :domain => env['LOCAL_DOMAIN'],
  216. :authentication => :plain,
  217. :enable_starttls_auto => true,
  218. }
  219. ActionMailer::Base.default_options = {
  220. from: env['SMTP_FROM_ADDRESS'],
  221. }
  222. mail = ActionMailer::Base.new.mail to: send_to, subject: 'Test', body: 'Mastodon SMTP configuration works!'
  223. mail.deliver
  224. rescue StandardError => e
  225. prompt.error 'E-mail could not be sent with this configuration, try again.'
  226. prompt.error e.message
  227. break unless prompt.yes?('Try again?')
  228. end
  229. end
  230. prompt.say "\n"
  231. prompt.say 'This configuration will be written to .env.production'
  232. if prompt.yes?('Save configuration?')
  233. cmd = TTY::Command.new(printer: :quiet)
  234. File.write(Rails.root.join('.env.production'), "# Generated with mastodon:setup on #{Time.now.utc}\n\n" + env.each_pair.map { |key, value| "#{key}=#{value}" }.join("\n") + "\n")
  235. if using_docker
  236. prompt.ok 'Below is your configuration, save it to an .env.production file outside Docker:'
  237. prompt.say "\n"
  238. prompt.say File.read(Rails.root.join('.env.production'))
  239. prompt.say "\n"
  240. prompt.ok 'It is also saved within this container so you can proceed with this wizard.'
  241. end
  242. prompt.say "\n"
  243. prompt.say 'Now that configuration is saved, the database schema must be loaded.'
  244. prompt.warn 'If the database already exists, this will erase its contents.'
  245. if prompt.yes?('Prepare the database now?')
  246. prompt.say 'Running `RAILS_ENV=production rails db:setup` ...'
  247. prompt.say "\n"
  248. if cmd.run!({ RAILS_ENV: 'production' }, :rails, 'db:setup').failure?
  249. prompt.say "\n"
  250. prompt.error 'That failed! Perhaps your configuration is not right'
  251. else
  252. prompt.say "\n"
  253. prompt.ok 'Done!'
  254. end
  255. end
  256. prompt.say "\n"
  257. prompt.say 'The final step is compiling CSS/JS assets.'
  258. prompt.say 'This may take a while and consume a lot of RAM.'
  259. if prompt.yes?('Compile the assets now?')
  260. prompt.say 'Running `RAILS_ENV=production rails assets:precompile` ...'
  261. prompt.say "\n"
  262. if cmd.run!({ RAILS_ENV: 'production' }, :rails, 'assets:precompile').failure?
  263. prompt.say "\n"
  264. prompt.error 'That failed! Maybe you need swap space?'
  265. else
  266. prompt.say "\n"
  267. prompt.say 'Done!'
  268. end
  269. end
  270. prompt.say "\n"
  271. prompt.ok 'All done! You can now power on the Mastodon server 🐘'
  272. prompt.say "\n"
  273. if db_connection_works && prompt.yes?('Do you want to create an admin user straight away?')
  274. env.each_pair do |key, value|
  275. ENV[key] = value.to_s
  276. end
  277. require_relative '../../config/environment'
  278. disable_log_stdout!
  279. username = prompt.ask('Username:') do |q|
  280. q.required true
  281. q.default 'admin'
  282. q.validate(/\A[a-z0-9_]+\z/i)
  283. q.modify :strip
  284. end
  285. email = prompt.ask('E-mail:') do |q|
  286. q.required true
  287. q.modify :strip
  288. end
  289. password = SecureRandom.hex(16)
  290. user = User.new(admin: true, email: email, password: password, confirmed_at: Time.now.utc, account_attributes: { username: username })
  291. user.save(validate: false)
  292. prompt.ok "You can login with the password: #{password}"
  293. prompt.warn 'You can change your password once you login.'
  294. end
  295. else
  296. prompt.warn 'Nothing saved. Bye!'
  297. end
  298. rescue TTY::Reader::InputInterrupt
  299. prompt.ok 'Aborting. Bye!'
  300. end
  301. end
  302. desc 'Execute daily tasks (deprecated)'
  303. task :daily do
  304. # No-op
  305. # All of these tasks are now executed via sidekiq-scheduler
  306. end
  307. desc 'Turn a user into an admin, identified by the USERNAME environment variable'
  308. task make_admin: :environment do
  309. include RoutingHelper
  310. account_username = ENV.fetch('USERNAME')
  311. user = User.joins(:account).where(accounts: { username: account_username })
  312. if user.present?
  313. user.update(admin: true)
  314. puts "Congrats! #{account_username} is now an admin. \\o/\nNavigate to #{edit_admin_settings_url} to get started"
  315. else
  316. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  317. end
  318. end
  319. desc 'Turn a user into a moderator, identified by the USERNAME environment variable'
  320. task make_mod: :environment do
  321. account_username = ENV.fetch('USERNAME')
  322. user = User.joins(:account).where(accounts: { username: account_username })
  323. if user.present?
  324. user.update(moderator: true)
  325. puts "Congrats! #{account_username} is now a moderator \\o/"
  326. else
  327. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  328. end
  329. end
  330. desc 'Remove admin and moderator privileges from user identified by the USERNAME environment variable'
  331. task revoke_staff: :environment do
  332. account_username = ENV.fetch('USERNAME')
  333. user = User.joins(:account).where(accounts: { username: account_username })
  334. if user.present?
  335. user.update(moderator: false, admin: false)
  336. puts "#{account_username} is no longer admin or moderator."
  337. else
  338. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  339. end
  340. end
  341. desc 'Manually confirms a user with associated user email address stored in USER_EMAIL environment variable.'
  342. task confirm_email: :environment do
  343. email = ENV.fetch('USER_EMAIL')
  344. user = User.find_by(email: email)
  345. if user
  346. user.update(confirmed_at: Time.now.utc)
  347. puts "#{email} confirmed"
  348. else
  349. abort "#{email} not found"
  350. end
  351. end
  352. desc 'Add a user by providing their email, username and initial password.' \
  353. 'The user will receive a confirmation email, then they must reset their password before logging in.'
  354. task add_user: :environment do
  355. disable_log_stdout!
  356. prompt = TTY::Prompt.new
  357. begin
  358. email = prompt.ask('E-mail:', required: true) do |q|
  359. q.modify :strip
  360. end
  361. username = prompt.ask('Username:', required: true) do |q|
  362. q.modify :strip
  363. end
  364. role = prompt.select('Role:', %w(user moderator admin))
  365. if prompt.yes?('Proceed to create the user?')
  366. user = User.new(email: email, password: SecureRandom.hex, admin: role == 'admin', moderator: role == 'moderator', account_attributes: { username: username })
  367. if user.save
  368. prompt.ok 'User created and confirmation mail sent to the user\'s email address.'
  369. prompt.ok "Here is the random password generated for the user: #{password}"
  370. else
  371. prompt.warn 'User was not created because of the following errors:'
  372. user.errors.each do |key, val|
  373. prompt.error "#{key}: #{val}"
  374. end
  375. end
  376. else
  377. prompt.ok 'Aborting. Bye!'
  378. end
  379. rescue TTY::Reader::InputInterrupt
  380. prompt.ok 'Aborting. Bye!'
  381. end
  382. end
  383. namespace :media do
  384. desc 'Removes media attachments that have not been assigned to any status for longer than a day (deprecated)'
  385. task clear: :environment do
  386. # No-op
  387. # This task is now executed via sidekiq-scheduler
  388. end
  389. desc 'Remove media attachments attributed to silenced accounts'
  390. task remove_silenced: :environment do
  391. MediaAttachment.where(account: Account.silenced).find_each(&:destroy)
  392. end
  393. desc 'Remove cached remote media attachments that are older than NUM_DAYS. By default 7 (week)'
  394. task remove_remote: :environment do
  395. time_ago = ENV.fetch('NUM_DAYS') { 7 }.to_i.days.ago
  396. MediaAttachment.where.not(remote_url: '').where.not(file_file_name: nil).where('created_at < ?', time_ago).find_each do |media|
  397. next unless media.file.exists?
  398. media.file.destroy
  399. media.save
  400. end
  401. end
  402. desc 'Set unknown attachment type for remote-only attachments'
  403. task set_unknown: :environment do
  404. puts 'Setting unknown attachment type for remote-only attachments...'
  405. MediaAttachment.where(file_file_name: nil).where.not(type: :unknown).in_batches.update_all(type: :unknown)
  406. puts 'Done!'
  407. end
  408. desc 'Redownload avatars/headers of remote users. Optionally limit to a particular domain with DOMAIN'
  409. task redownload_avatars: :environment do
  410. accounts = Account.remote
  411. accounts = accounts.where(domain: ENV['DOMAIN']) if ENV['DOMAIN'].present?
  412. accounts.find_each do |account|
  413. begin
  414. account.reset_avatar!
  415. account.reset_header!
  416. account.save
  417. rescue Paperclip::Error
  418. puts "Error resetting avatar and header for account #{username}@#{domain}"
  419. end
  420. end
  421. end
  422. end
  423. namespace :push do
  424. desc 'Unsubscribes from PuSH updates of feeds nobody follows locally'
  425. task clear: :environment do
  426. Pubsubhubbub::UnsubscribeWorker.push_bulk(Account.remote.without_followers.where.not(subscription_expires_at: nil).pluck(:id))
  427. end
  428. desc 'Re-subscribes to soon expiring PuSH subscriptions (deprecated)'
  429. task refresh: :environment do
  430. # No-op
  431. # This task is now executed via sidekiq-scheduler
  432. end
  433. end
  434. namespace :feeds do
  435. desc 'Clear timelines of inactive users (deprecated)'
  436. task clear: :environment do
  437. # No-op
  438. # This task is now executed via sidekiq-scheduler
  439. end
  440. desc 'Clear all timelines without regenerating them'
  441. task clear_all: :environment do
  442. Redis.current.keys('feed:*').each { |key| Redis.current.del(key) }
  443. end
  444. desc 'Generates home timelines for users who logged in in the past two weeks'
  445. task build: :environment do
  446. User.active.includes(:account).find_each do |u|
  447. PrecomputeFeedService.new.call(u.account)
  448. end
  449. end
  450. end
  451. namespace :emails do
  452. desc 'Send out digest e-mails (deprecated)'
  453. task digest: :environment do
  454. # No-op
  455. # This task is now executed via sidekiq-scheduler
  456. end
  457. end
  458. namespace :users do
  459. desc 'Clear out unconfirmed users (deprecated)'
  460. task clear: :environment do
  461. # No-op
  462. # This task is now executed via sidekiq-scheduler
  463. end
  464. desc 'List e-mails of all admin users'
  465. task admins: :environment do
  466. puts 'Admin user emails:'
  467. puts User.admins.map(&:email).join("\n")
  468. end
  469. end
  470. namespace :settings do
  471. desc 'Open registrations on this instance'
  472. task open_registrations: :environment do
  473. Setting.open_registrations = true
  474. end
  475. desc 'Close registrations on this instance'
  476. task close_registrations: :environment do
  477. Setting.open_registrations = false
  478. end
  479. end
  480. namespace :webpush do
  481. desc 'Generate VAPID key'
  482. task generate_vapid_key: :environment do
  483. vapid_key = Webpush.generate_key
  484. puts "VAPID_PRIVATE_KEY=#{vapid_key.private_key}"
  485. puts "VAPID_PUBLIC_KEY=#{vapid_key.public_key}"
  486. end
  487. end
  488. namespace :maintenance do
  489. desc 'Update counter caches'
  490. task update_counter_caches: :environment do
  491. puts 'Updating counter caches for accounts...'
  492. Account.unscoped.where.not(protocol: :activitypub).select('id').find_in_batches do |batch|
  493. Account.where(id: batch.map(&:id)).update_all('statuses_count = (select count(*) from statuses where account_id = accounts.id), followers_count = (select count(*) from follows where target_account_id = accounts.id), following_count = (select count(*) from follows where account_id = accounts.id)')
  494. end
  495. puts 'Updating counter caches for statuses...'
  496. Status.unscoped.select('id').find_in_batches do |batch|
  497. Status.where(id: batch.map(&:id)).update_all('favourites_count = (select count(*) from favourites where favourites.status_id = statuses.id), reblogs_count = (select count(*) from statuses as reblogs where reblogs.reblog_of_id = statuses.id)')
  498. end
  499. puts 'Done!'
  500. end
  501. desc 'Generate static versions of GIF avatars/headers'
  502. task add_static_avatars: :environment do
  503. puts 'Generating static avatars/headers for GIF ones...'
  504. Account.unscoped.where(avatar_content_type: 'image/gif').or(Account.unscoped.where(header_content_type: 'image/gif')).find_each do |account|
  505. begin
  506. account.avatar.reprocess! if account.avatar_content_type == 'image/gif' && !account.avatar.exists?(:static)
  507. account.header.reprocess! if account.header_content_type == 'image/gif' && !account.header.exists?(:static)
  508. rescue StandardError => e
  509. Rails.logger.error "Error while generating static avatars/headers for account #{account.id}: #{e}"
  510. next
  511. end
  512. end
  513. puts 'Done!'
  514. end
  515. desc 'Ensure referencial integrity'
  516. task prepare_for_foreign_keys: :environment do
  517. # All the deletes:
  518. ActiveRecord::Base.connection.execute('DELETE FROM statuses USING statuses s LEFT JOIN accounts a ON a.id = s.account_id WHERE statuses.id = s.id AND a.id IS NULL')
  519. if ActiveRecord::Base.connection.table_exists? :account_domain_blocks
  520. ActiveRecord::Base.connection.execute('DELETE FROM account_domain_blocks USING account_domain_blocks adb LEFT JOIN accounts a ON a.id = adb.account_id WHERE account_domain_blocks.id = adb.id AND a.id IS NULL')
  521. end
  522. if ActiveRecord::Base.connection.table_exists? :conversation_mutes
  523. ActiveRecord::Base.connection.execute('DELETE FROM conversation_mutes USING conversation_mutes cm LEFT JOIN accounts a ON a.id = cm.account_id WHERE conversation_mutes.id = cm.id AND a.id IS NULL')
  524. ActiveRecord::Base.connection.execute('DELETE FROM conversation_mutes USING conversation_mutes cm LEFT JOIN conversations c ON c.id = cm.conversation_id WHERE conversation_mutes.id = cm.id AND c.id IS NULL')
  525. end
  526. ActiveRecord::Base.connection.execute('DELETE FROM favourites USING favourites f LEFT JOIN accounts a ON a.id = f.account_id WHERE favourites.id = f.id AND a.id IS NULL')
  527. ActiveRecord::Base.connection.execute('DELETE FROM favourites USING favourites f LEFT JOIN statuses s ON s.id = f.status_id WHERE favourites.id = f.id AND s.id IS NULL')
  528. ActiveRecord::Base.connection.execute('DELETE FROM blocks USING blocks b LEFT JOIN accounts a ON a.id = b.account_id WHERE blocks.id = b.id AND a.id IS NULL')
  529. ActiveRecord::Base.connection.execute('DELETE FROM blocks USING blocks b LEFT JOIN accounts a ON a.id = b.target_account_id WHERE blocks.id = b.id AND a.id IS NULL')
  530. ActiveRecord::Base.connection.execute('DELETE FROM follow_requests USING follow_requests fr LEFT JOIN accounts a ON a.id = fr.account_id WHERE follow_requests.id = fr.id AND a.id IS NULL')
  531. ActiveRecord::Base.connection.execute('DELETE FROM follow_requests USING follow_requests fr LEFT JOIN accounts a ON a.id = fr.target_account_id WHERE follow_requests.id = fr.id AND a.id IS NULL')
  532. ActiveRecord::Base.connection.execute('DELETE FROM follows USING follows f LEFT JOIN accounts a ON a.id = f.account_id WHERE follows.id = f.id AND a.id IS NULL')
  533. ActiveRecord::Base.connection.execute('DELETE FROM follows USING follows f LEFT JOIN accounts a ON a.id = f.target_account_id WHERE follows.id = f.id AND a.id IS NULL')
  534. ActiveRecord::Base.connection.execute('DELETE FROM mutes USING mutes m LEFT JOIN accounts a ON a.id = m.account_id WHERE mutes.id = m.id AND a.id IS NULL')
  535. ActiveRecord::Base.connection.execute('DELETE FROM mutes USING mutes m LEFT JOIN accounts a ON a.id = m.target_account_id WHERE mutes.id = m.id AND a.id IS NULL')
  536. ActiveRecord::Base.connection.execute('DELETE FROM imports USING imports i LEFT JOIN accounts a ON a.id = i.account_id WHERE imports.id = i.id AND a.id IS NULL')
  537. ActiveRecord::Base.connection.execute('DELETE FROM mentions USING mentions m LEFT JOIN accounts a ON a.id = m.account_id WHERE mentions.id = m.id AND a.id IS NULL')
  538. ActiveRecord::Base.connection.execute('DELETE FROM mentions USING mentions m LEFT JOIN statuses s ON s.id = m.status_id WHERE mentions.id = m.id AND s.id IS NULL')
  539. ActiveRecord::Base.connection.execute('DELETE FROM notifications USING notifications n LEFT JOIN accounts a ON a.id = n.account_id WHERE notifications.id = n.id AND a.id IS NULL')
  540. ActiveRecord::Base.connection.execute('DELETE FROM notifications USING notifications n LEFT JOIN accounts a ON a.id = n.from_account_id WHERE notifications.id = n.id AND a.id IS NULL')
  541. ActiveRecord::Base.connection.execute('DELETE FROM preview_cards USING preview_cards pc LEFT JOIN statuses s ON s.id = pc.status_id WHERE preview_cards.id = pc.id AND s.id IS NULL')
  542. ActiveRecord::Base.connection.execute('DELETE FROM reports USING reports r LEFT JOIN accounts a ON a.id = r.account_id WHERE reports.id = r.id AND a.id IS NULL')
  543. ActiveRecord::Base.connection.execute('DELETE FROM reports USING reports r LEFT JOIN accounts a ON a.id = r.target_account_id WHERE reports.id = r.id AND a.id IS NULL')
  544. ActiveRecord::Base.connection.execute('DELETE FROM statuses_tags USING statuses_tags st LEFT JOIN statuses s ON s.id = st.status_id WHERE statuses_tags.tag_id = st.tag_id AND statuses_tags.status_id = st.status_id AND s.id IS NULL')
  545. ActiveRecord::Base.connection.execute('DELETE FROM statuses_tags USING statuses_tags st LEFT JOIN tags t ON t.id = st.tag_id WHERE statuses_tags.tag_id = st.tag_id AND statuses_tags.status_id = st.status_id AND t.id IS NULL')
  546. ActiveRecord::Base.connection.execute('DELETE FROM stream_entries USING stream_entries se LEFT JOIN accounts a ON a.id = se.account_id WHERE stream_entries.id = se.id AND a.id IS NULL')
  547. ActiveRecord::Base.connection.execute('DELETE FROM subscriptions USING subscriptions s LEFT JOIN accounts a ON a.id = s.account_id WHERE subscriptions.id = s.id AND a.id IS NULL')
  548. ActiveRecord::Base.connection.execute('DELETE FROM users USING users u LEFT JOIN accounts a ON a.id = u.account_id WHERE users.id = u.id AND a.id IS NULL')
  549. ActiveRecord::Base.connection.execute('DELETE FROM web_settings USING web_settings ws LEFT JOIN users u ON u.id = ws.user_id WHERE web_settings.id = ws.id AND u.id IS NULL')
  550. ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_grants USING oauth_access_grants oag LEFT JOIN users u ON u.id = oag.resource_owner_id WHERE oauth_access_grants.id = oag.id AND oag.resource_owner_id IS NOT NULL AND u.id IS NULL')
  551. ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_grants USING oauth_access_grants oag LEFT JOIN oauth_applications a ON a.id = oag.application_id WHERE oauth_access_grants.id = oag.id AND oag.application_id IS NOT NULL AND a.id IS NULL')
  552. ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_tokens USING oauth_access_tokens oat LEFT JOIN users u ON u.id = oat.resource_owner_id WHERE oauth_access_tokens.id = oat.id AND oat.resource_owner_id IS NOT NULL AND u.id IS NULL')
  553. ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_tokens USING oauth_access_tokens oat LEFT JOIN oauth_applications a ON a.id = oat.application_id WHERE oauth_access_tokens.id = oat.id AND oat.application_id IS NOT NULL AND a.id IS NULL')
  554. # All the nullifies:
  555. ActiveRecord::Base.connection.execute('UPDATE statuses SET in_reply_to_id = NULL FROM statuses s LEFT JOIN statuses rs ON rs.id = s.in_reply_to_id WHERE statuses.id = s.id AND s.in_reply_to_id IS NOT NULL AND rs.id IS NULL')
  556. ActiveRecord::Base.connection.execute('UPDATE statuses SET in_reply_to_account_id = NULL FROM statuses s LEFT JOIN accounts a ON a.id = s.in_reply_to_account_id WHERE statuses.id = s.id AND s.in_reply_to_account_id IS NOT NULL AND a.id IS NULL')
  557. ActiveRecord::Base.connection.execute('UPDATE media_attachments SET status_id = NULL FROM media_attachments ma LEFT JOIN statuses s ON s.id = ma.status_id WHERE media_attachments.id = ma.id AND ma.status_id IS NOT NULL AND s.id IS NULL')
  558. ActiveRecord::Base.connection.execute('UPDATE media_attachments SET account_id = NULL FROM media_attachments ma LEFT JOIN accounts a ON a.id = ma.account_id WHERE media_attachments.id = ma.id AND ma.account_id IS NOT NULL AND a.id IS NULL')
  559. ActiveRecord::Base.connection.execute('UPDATE reports SET action_taken_by_account_id = NULL FROM reports r LEFT JOIN accounts a ON a.id = r.action_taken_by_account_id WHERE reports.id = r.id AND r.action_taken_by_account_id IS NOT NULL AND a.id IS NULL')
  560. end
  561. desc 'Remove deprecated preview cards'
  562. task remove_deprecated_preview_cards: :environment do
  563. next unless ActiveRecord::Base.connection.table_exists? 'deprecated_preview_cards'
  564. class DeprecatedPreviewCard < ActiveRecord::Base
  565. self.inheritance_column = false
  566. path = '/preview_cards/:attachment/:id_partition/:style/:filename'
  567. if ENV['S3_ENABLED'] != 'true'
  568. path = (ENV['PAPERCLIP_ROOT_PATH'] || ':rails_root/public/system') + path
  569. end
  570. has_attached_file :image, styles: { original: '280x120>' }, convert_options: { all: '-quality 80 -strip' }, path: path
  571. end
  572. puts 'Delete records and associated files from deprecated preview cards? [y/N]: '
  573. confirm = STDIN.gets.chomp
  574. if confirm.casecmp('y').zero?
  575. DeprecatedPreviewCard.in_batches.destroy_all
  576. puts 'Drop deprecated preview cards table? [y/N]: '
  577. confirm = STDIN.gets.chomp
  578. if confirm.casecmp('y').zero?
  579. ActiveRecord::Migration.drop_table :deprecated_preview_cards
  580. end
  581. end
  582. end
  583. desc 'Migrate photo preview cards made before 2.1'
  584. task migrate_photo_preview_cards: :environment do
  585. status_ids = Status.joins(:preview_cards)
  586. .where(preview_cards: { embed_url: '', type: :photo })
  587. .reorder(nil)
  588. .group(:id)
  589. .pluck(:id)
  590. PreviewCard.where(embed_url: '', type: :photo).delete_all
  591. LinkCrawlWorker.push_bulk status_ids
  592. end
  593. desc 'Remove all home feed regeneration markers'
  594. task remove_regeneration_markers: :environment do
  595. keys = Redis.current.keys('account:*:regeneration')
  596. Redis.current.pipelined do
  597. keys.each { |key| Redis.current.del(key) }
  598. end
  599. end
  600. desc 'Check every known remote account and delete those that no longer exist in origin'
  601. task purge_removed_accounts: :environment do
  602. prepare_for_options!
  603. options = {}
  604. OptionParser.new do |opts|
  605. opts.banner = 'Usage: rails mastodon:maintenance:purge_removed_accounts [options]'
  606. opts.on('-f', '--force', 'Remove all encountered accounts without asking for confirmation') do
  607. options[:force] = true
  608. end
  609. opts.on('-h', '--help', 'Display this message') do
  610. puts opts
  611. exit
  612. end
  613. end.parse!
  614. disable_log_stdout!
  615. total = Account.remote.where(protocol: :activitypub).count
  616. progress_bar = ProgressBar.create(total: total, format: '%c/%C |%w>%i| %e')
  617. Account.remote.where(protocol: :activitypub).partitioned.find_each do |account|
  618. progress_bar.increment
  619. begin
  620. res = Request.new(:head, account.uri).perform
  621. rescue StandardError
  622. # This could happen due to network timeout, DNS timeout, wrong SSL cert, etc,
  623. # which should probably not lead to perceiving the account as deleted, so
  624. # just skip till next time
  625. next
  626. end
  627. if [404, 410].include?(res.code)
  628. if options[:force]
  629. SuspendAccountService.new.call(account)
  630. account.destroy
  631. else
  632. progress_bar.pause
  633. progress_bar.clear
  634. print "\nIt seems like #{account.acct} no longer exists. Purge the account from the database? [Y/n]: ".colorize(:yellow)
  635. confirm = STDIN.gets.chomp
  636. puts ''
  637. progress_bar.resume
  638. if confirm.casecmp('n').zero?
  639. next
  640. else
  641. SuspendAccountService.new.call(account)
  642. account.destroy
  643. end
  644. end
  645. end
  646. end
  647. end
  648. end
  649. end
  650. def disable_log_stdout!
  651. dev_null = Logger.new('/dev/null')
  652. Rails.logger = dev_null
  653. ActiveRecord::Base.logger = dev_null
  654. HttpLog.configuration.logger = dev_null
  655. Paperclip.options[:log] = false
  656. end
  657. def prepare_for_options!
  658. 2.times { ARGV.shift }
  659. end