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.

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