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.

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