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.

824 lines
33 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. if prompt.yes?('Do you want to send e-mails from localhost?', default: false)
  187. env['SMTP_SERVER'] = 'localhost'
  188. env['SMTP_PORT'] = 25
  189. env['SMTP_AUTH_METHOD'] = 'none'
  190. env['SMTP_OPENSSL_VERIFY_MODE'] = 'none'
  191. else
  192. env['SMTP_SERVER'] = prompt.ask('SMTP server:') do |q|
  193. q.required true
  194. q.default 'smtp.mailgun.org'
  195. q.modify :strip
  196. end
  197. env['SMTP_PORT'] = prompt.ask('SMTP port:') do |q|
  198. q.required true
  199. q.default 587
  200. q.convert :int
  201. end
  202. env['SMTP_LOGIN'] = prompt.ask('SMTP username:') do |q|
  203. q.modify :strip
  204. end
  205. env['SMTP_PASSWORD'] = prompt.ask('SMTP password:') do |q|
  206. q.echo false
  207. end
  208. env['SMTP_AUTH_METHOD'] = prompt.ask('SMTP authentication:') do |q|
  209. q.required
  210. q.default 'plain'
  211. q.modify :strip
  212. end
  213. env['SMTP_OPENSSL_VERIFY_MODE'] = prompt.ask('SMTP OpenSSL verify mode:') do |q|
  214. q.required
  215. q.default 'peer'
  216. q.modify :strip
  217. end
  218. end
  219. env['SMTP_FROM_ADDRESS'] = prompt.ask('E-mail address to send e-mails "from":') do |q|
  220. q.required true
  221. q.default "Mastodon <notifications@#{env['LOCAL_DOMAIN']}>"
  222. q.modify :strip
  223. end
  224. break unless prompt.yes?('Send a test e-mail with this configuration right now?')
  225. send_to = prompt.ask('Send test e-mail to:', required: true)
  226. begin
  227. ActionMailer::Base.smtp_settings = {
  228. :port => env['SMTP_PORT'],
  229. :address => env['SMTP_SERVER'],
  230. :user_name => env['SMTP_LOGIN'].presence,
  231. :password => env['SMTP_PASSWORD'].presence,
  232. :domain => env['LOCAL_DOMAIN'],
  233. :authentication => env['SMTP_AUTH_METHOD'] == 'none' ? nil : env['SMTP_AUTH_METHOD'] || :plain,
  234. :openssl_verify_mode => env['SMTP_OPENSSL_VERIFY_MODE'],
  235. :enable_starttls_auto => true,
  236. }
  237. ActionMailer::Base.default_options = {
  238. from: env['SMTP_FROM_ADDRESS'],
  239. }
  240. mail = ActionMailer::Base.new.mail to: send_to, subject: 'Test', body: 'Mastodon SMTP configuration works!'
  241. mail.deliver
  242. break
  243. rescue StandardError => e
  244. prompt.error 'E-mail could not be sent with this configuration, try again.'
  245. prompt.error e.message
  246. break unless prompt.yes?('Try again?')
  247. end
  248. end
  249. prompt.say "\n"
  250. prompt.say 'This configuration will be written to .env.production'
  251. if prompt.yes?('Save configuration?')
  252. cmd = TTY::Command.new(printer: :quiet)
  253. 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")
  254. if using_docker
  255. prompt.ok 'Below is your configuration, save it to an .env.production file outside Docker:'
  256. prompt.say "\n"
  257. prompt.say File.read(Rails.root.join('.env.production'))
  258. prompt.say "\n"
  259. prompt.ok 'It is also saved within this container so you can proceed with this wizard.'
  260. end
  261. prompt.say "\n"
  262. prompt.say 'Now that configuration is saved, the database schema must be loaded.'
  263. prompt.warn 'If the database already exists, this will erase its contents.'
  264. if prompt.yes?('Prepare the database now?')
  265. prompt.say 'Running `RAILS_ENV=production rails db:setup` ...'
  266. prompt.say "\n"
  267. if cmd.run!({ RAILS_ENV: 'production', SAFETY_ASSURED: 1 }, :rails, 'db:setup').failure?
  268. prompt.say "\n"
  269. prompt.error 'That failed! Perhaps your configuration is not right'
  270. else
  271. prompt.say "\n"
  272. prompt.ok 'Done!'
  273. end
  274. end
  275. prompt.say "\n"
  276. prompt.say 'The final step is compiling CSS/JS assets.'
  277. prompt.say 'This may take a while and consume a lot of RAM.'
  278. if prompt.yes?('Compile the assets now?')
  279. prompt.say 'Running `RAILS_ENV=production rails assets:precompile` ...'
  280. prompt.say "\n"
  281. if cmd.run!({ RAILS_ENV: 'production' }, :rails, 'assets:precompile').failure?
  282. prompt.say "\n"
  283. prompt.error 'That failed! Maybe you need swap space?'
  284. else
  285. prompt.say "\n"
  286. prompt.say 'Done!'
  287. end
  288. end
  289. prompt.say "\n"
  290. prompt.ok 'All done! You can now power on the Mastodon server 🐘'
  291. prompt.say "\n"
  292. if db_connection_works && prompt.yes?('Do you want to create an admin user straight away?')
  293. env.each_pair do |key, value|
  294. ENV[key] = value.to_s
  295. end
  296. require_relative '../../config/environment'
  297. disable_log_stdout!
  298. username = prompt.ask('Username:') do |q|
  299. q.required true
  300. q.default 'admin'
  301. q.validate(/\A[a-z0-9_]+\z/i)
  302. q.modify :strip
  303. end
  304. email = prompt.ask('E-mail:') do |q|
  305. q.required true
  306. q.modify :strip
  307. end
  308. password = SecureRandom.hex(16)
  309. user = User.new(admin: true, email: email, password: password, confirmed_at: Time.now.utc, account_attributes: { username: username })
  310. user.save(validate: false)
  311. prompt.ok "You can login with the password: #{password}"
  312. prompt.warn 'You can change your password once you login.'
  313. end
  314. else
  315. prompt.warn 'Nothing saved. Bye!'
  316. end
  317. rescue TTY::Reader::InputInterrupt
  318. prompt.ok 'Aborting. Bye!'
  319. end
  320. end
  321. desc 'Execute daily tasks (deprecated)'
  322. task :daily do
  323. # No-op
  324. # All of these tasks are now executed via sidekiq-scheduler
  325. end
  326. desc 'Turn a user into an admin, identified by the USERNAME environment variable'
  327. task make_admin: :environment do
  328. include RoutingHelper
  329. account_username = ENV.fetch('USERNAME')
  330. user = User.joins(:account).where(accounts: { username: account_username })
  331. if user.present?
  332. user.update(admin: true)
  333. puts "Congrats! #{account_username} is now an admin. \\o/\nNavigate to #{edit_admin_settings_url} to get started"
  334. else
  335. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  336. end
  337. end
  338. desc 'Turn a user into a moderator, identified by the USERNAME environment variable'
  339. task make_mod: :environment do
  340. account_username = ENV.fetch('USERNAME')
  341. user = User.joins(:account).where(accounts: { username: account_username })
  342. if user.present?
  343. user.update(moderator: true)
  344. puts "Congrats! #{account_username} is now a moderator \\o/"
  345. else
  346. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  347. end
  348. end
  349. desc 'Remove admin and moderator privileges from user identified by the USERNAME environment variable'
  350. task revoke_staff: :environment do
  351. account_username = ENV.fetch('USERNAME')
  352. user = User.joins(:account).where(accounts: { username: account_username })
  353. if user.present?
  354. user.update(moderator: false, admin: false)
  355. puts "#{account_username} is no longer admin or moderator."
  356. else
  357. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  358. end
  359. end
  360. desc 'Manually confirms a user with associated user email address stored in USER_EMAIL environment variable.'
  361. task confirm_email: :environment do
  362. email = ENV.fetch('USER_EMAIL')
  363. user = User.find_by(email: email)
  364. if user
  365. user.update(confirmed_at: Time.now.utc)
  366. puts "#{email} confirmed"
  367. else
  368. abort "#{email} not found"
  369. end
  370. end
  371. desc 'Add a user by providing their email, username and initial password.' \
  372. 'The user will receive a confirmation email, then they must reset their password before logging in.'
  373. task add_user: :environment do
  374. disable_log_stdout!
  375. prompt = TTY::Prompt.new
  376. begin
  377. email = prompt.ask('E-mail:', required: true) do |q|
  378. q.modify :strip
  379. end
  380. username = prompt.ask('Username:', required: true) do |q|
  381. q.modify :strip
  382. end
  383. role = prompt.select('Role:', %w(user moderator admin))
  384. if prompt.yes?('Proceed to create the user?')
  385. user = User.new(email: email, password: SecureRandom.hex, admin: role == 'admin', moderator: role == 'moderator', account_attributes: { username: username })
  386. if user.save
  387. prompt.ok 'User created and confirmation mail sent to the user\'s email address.'
  388. prompt.ok "Here is the random password generated for the user: #{user.password}"
  389. else
  390. prompt.warn 'User was not created because of the following errors:'
  391. user.errors.each do |key, val|
  392. prompt.error "#{key}: #{val}"
  393. end
  394. end
  395. else
  396. prompt.ok 'Aborting. Bye!'
  397. end
  398. rescue TTY::Reader::InputInterrupt
  399. prompt.ok 'Aborting. Bye!'
  400. end
  401. end
  402. namespace :media do
  403. desc 'Removes media attachments that have not been assigned to any status for longer than a day (deprecated)'
  404. task clear: :environment do
  405. # No-op
  406. # This task is now executed via sidekiq-scheduler
  407. end
  408. desc 'Remove media attachments attributed to silenced accounts'
  409. task remove_silenced: :environment do
  410. MediaAttachment.where(account: Account.silenced).find_each(&:destroy)
  411. end
  412. desc 'Remove cached remote media attachments that are older than NUM_DAYS. By default 7 (week)'
  413. task remove_remote: :environment do
  414. time_ago = ENV.fetch('NUM_DAYS') { 7 }.to_i.days.ago
  415. MediaAttachment.where.not(remote_url: '').where.not(file_file_name: nil).where('created_at < ?', time_ago).find_each do |media|
  416. next unless media.file.exists?
  417. media.file.destroy
  418. media.save
  419. end
  420. end
  421. desc 'Set unknown attachment type for remote-only attachments'
  422. task set_unknown: :environment do
  423. puts 'Setting unknown attachment type for remote-only attachments...'
  424. MediaAttachment.where(file_file_name: nil).where.not(type: :unknown).in_batches.update_all(type: :unknown)
  425. puts 'Done!'
  426. end
  427. desc 'Redownload avatars/headers of remote users. Optionally limit to a particular domain with DOMAIN'
  428. task redownload_avatars: :environment do
  429. accounts = Account.remote
  430. accounts = accounts.where(domain: ENV['DOMAIN']) if ENV['DOMAIN'].present?
  431. accounts.find_each do |account|
  432. begin
  433. account.reset_avatar!
  434. account.reset_header!
  435. account.save
  436. rescue Paperclip::Error
  437. puts "Error resetting avatar and header for account #{username}@#{domain}"
  438. end
  439. end
  440. end
  441. end
  442. namespace :push do
  443. desc 'Unsubscribes from PuSH updates of feeds nobody follows locally'
  444. task clear: :environment do
  445. Pubsubhubbub::UnsubscribeWorker.push_bulk(Account.remote.without_followers.where.not(subscription_expires_at: nil).pluck(:id))
  446. end
  447. desc 'Re-subscribes to soon expiring PuSH subscriptions (deprecated)'
  448. task refresh: :environment do
  449. # No-op
  450. # This task is now executed via sidekiq-scheduler
  451. end
  452. end
  453. namespace :feeds do
  454. desc 'Clear timelines of inactive users (deprecated)'
  455. task clear: :environment do
  456. # No-op
  457. # This task is now executed via sidekiq-scheduler
  458. end
  459. desc 'Clear all timelines without regenerating them'
  460. task clear_all: :environment do
  461. Redis.current.keys('feed:*').each { |key| Redis.current.del(key) }
  462. end
  463. desc 'Generates home timelines for users who logged in in the past two weeks'
  464. task build: :environment do
  465. User.active.includes(:account).find_each do |u|
  466. PrecomputeFeedService.new.call(u.account)
  467. end
  468. end
  469. end
  470. namespace :emails do
  471. desc 'Send out digest e-mails (deprecated)'
  472. task digest: :environment do
  473. # No-op
  474. # This task is now executed via sidekiq-scheduler
  475. end
  476. end
  477. namespace :users do
  478. desc 'Clear out unconfirmed users (deprecated)'
  479. task clear: :environment do
  480. # No-op
  481. # This task is now executed via sidekiq-scheduler
  482. end
  483. desc 'List e-mails of all admin users'
  484. task admins: :environment do
  485. puts 'Admin user emails:'
  486. puts User.admins.map(&:email).join("\n")
  487. end
  488. end
  489. namespace :settings do
  490. desc 'Open registrations on this instance'
  491. task open_registrations: :environment do
  492. Setting.open_registrations = true
  493. end
  494. desc 'Close registrations on this instance'
  495. task close_registrations: :environment do
  496. Setting.open_registrations = false
  497. end
  498. end
  499. namespace :webpush do
  500. desc 'Generate VAPID key'
  501. task generate_vapid_key: :environment do
  502. vapid_key = Webpush.generate_key
  503. puts "VAPID_PRIVATE_KEY=#{vapid_key.private_key}"
  504. puts "VAPID_PUBLIC_KEY=#{vapid_key.public_key}"
  505. end
  506. end
  507. namespace :maintenance do
  508. desc 'Update counter caches'
  509. task update_counter_caches: :environment do
  510. puts 'Updating counter caches for accounts...'
  511. Account.unscoped.where.not(protocol: :activitypub).select('id').find_in_batches do |batch|
  512. 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)')
  513. end
  514. puts 'Updating counter caches for statuses...'
  515. Status.unscoped.select('id').find_in_batches do |batch|
  516. 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)')
  517. end
  518. puts 'Done!'
  519. end
  520. desc 'Generate static versions of GIF avatars/headers'
  521. task add_static_avatars: :environment do
  522. puts 'Generating static avatars/headers for GIF ones...'
  523. Account.unscoped.where(avatar_content_type: 'image/gif').or(Account.unscoped.where(header_content_type: 'image/gif')).find_each do |account|
  524. begin
  525. account.avatar.reprocess! if account.avatar_content_type == 'image/gif' && !account.avatar.exists?(:static)
  526. account.header.reprocess! if account.header_content_type == 'image/gif' && !account.header.exists?(:static)
  527. rescue StandardError => e
  528. Rails.logger.error "Error while generating static avatars/headers for account #{account.id}: #{e}"
  529. next
  530. end
  531. end
  532. puts 'Done!'
  533. end
  534. desc 'Ensure referencial integrity'
  535. task prepare_for_foreign_keys: :environment do
  536. # All the deletes:
  537. 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')
  538. if ActiveRecord::Base.connection.table_exists? :account_domain_blocks
  539. 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')
  540. end
  541. if ActiveRecord::Base.connection.table_exists? :conversation_mutes
  542. 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')
  543. 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')
  544. end
  545. 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')
  546. 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')
  547. 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')
  548. 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')
  549. 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')
  550. 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')
  551. 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')
  552. 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')
  553. 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')
  554. 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')
  555. 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')
  556. 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')
  557. 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')
  558. 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')
  559. 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')
  560. 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')
  561. 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')
  562. 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')
  563. 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')
  564. 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')
  565. 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')
  566. 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')
  567. 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')
  568. 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')
  569. 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')
  570. 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')
  571. 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')
  572. 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')
  573. # All the nullifies:
  574. 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')
  575. 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')
  576. 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')
  577. 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')
  578. 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')
  579. end
  580. desc 'Remove deprecated preview cards'
  581. task remove_deprecated_preview_cards: :environment do
  582. next unless ActiveRecord::Base.connection.table_exists? 'deprecated_preview_cards'
  583. class DeprecatedPreviewCard < ActiveRecord::Base
  584. self.inheritance_column = false
  585. path = '/preview_cards/:attachment/:id_partition/:style/:filename'
  586. if ENV['S3_ENABLED'] != 'true'
  587. path = (ENV['PAPERCLIP_ROOT_PATH'] || ':rails_root/public/system') + path
  588. end
  589. has_attached_file :image, styles: { original: '280x120>' }, convert_options: { all: '-quality 80 -strip' }, path: path
  590. end
  591. puts 'Delete records and associated files from deprecated preview cards? [y/N]: '
  592. confirm = STDIN.gets.chomp
  593. if confirm.casecmp('y').zero?
  594. DeprecatedPreviewCard.in_batches.destroy_all
  595. puts 'Drop deprecated preview cards table? [y/N]: '
  596. confirm = STDIN.gets.chomp
  597. if confirm.casecmp('y').zero?
  598. ActiveRecord::Migration.drop_table :deprecated_preview_cards
  599. end
  600. end
  601. end
  602. desc 'Migrate photo preview cards made before 2.1'
  603. task migrate_photo_preview_cards: :environment do
  604. status_ids = Status.joins(:preview_cards)
  605. .where(preview_cards: { embed_url: '', type: :photo })
  606. .reorder(nil)
  607. .group(:id)
  608. .pluck(:id)
  609. PreviewCard.where(embed_url: '', type: :photo).delete_all
  610. LinkCrawlWorker.push_bulk status_ids
  611. end
  612. desc 'Remove all home feed regeneration markers'
  613. task remove_regeneration_markers: :environment do
  614. keys = Redis.current.keys('account:*:regeneration')
  615. Redis.current.pipelined do
  616. keys.each { |key| Redis.current.del(key) }
  617. end
  618. end
  619. desc 'Check every known remote account and delete those that no longer exist in origin'
  620. task purge_removed_accounts: :environment do
  621. prepare_for_options!
  622. options = {}
  623. OptionParser.new do |opts|
  624. opts.banner = 'Usage: rails mastodon:maintenance:purge_removed_accounts [options]'
  625. opts.on('-f', '--force', 'Remove all encountered accounts without asking for confirmation') do
  626. options[:force] = true
  627. end
  628. opts.on('-h', '--help', 'Display this message') do
  629. puts opts
  630. exit
  631. end
  632. end.parse!
  633. disable_log_stdout!
  634. total = Account.remote.where(protocol: :activitypub).count
  635. progress_bar = ProgressBar.create(total: total, format: '%c/%C |%w>%i| %e')
  636. Account.remote.where(protocol: :activitypub).partitioned.find_each do |account|
  637. progress_bar.increment
  638. begin
  639. code = Request.new(:head, account.uri).perform(&:code)
  640. rescue StandardError
  641. # This could happen due to network timeout, DNS timeout, wrong SSL cert, etc,
  642. # which should probably not lead to perceiving the account as deleted, so
  643. # just skip till next time
  644. next
  645. end
  646. if [404, 410].include?(code)
  647. if options[:force]
  648. SuspendAccountService.new.call(account)
  649. account.destroy
  650. else
  651. progress_bar.pause
  652. progress_bar.clear
  653. print "\nIt seems like #{account.acct} no longer exists. Purge the account from the database? [Y/n]: ".colorize(:yellow)
  654. confirm = STDIN.gets.chomp
  655. puts ''
  656. progress_bar.resume
  657. if confirm.casecmp('n').zero?
  658. next
  659. else
  660. SuspendAccountService.new.call(account)
  661. account.destroy
  662. end
  663. end
  664. end
  665. end
  666. end
  667. end
  668. end
  669. def disable_log_stdout!
  670. dev_null = Logger.new('/dev/null')
  671. Rails.logger = dev_null
  672. ActiveRecord::Base.logger = dev_null
  673. HttpLog.configuration.logger = dev_null
  674. Paperclip.options[:log] = false
  675. end
  676. def prepare_for_options!
  677. 2.times { ARGV.shift }
  678. end