The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

415 line
20 KiB

  1. # frozen_string_literal: true
  2. require 'optparse'
  3. require 'colorize'
  4. namespace :mastodon do
  5. desc 'Execute daily tasks (deprecated)'
  6. task :daily do
  7. # No-op
  8. # All of these tasks are now executed via sidekiq-scheduler
  9. end
  10. desc 'Turn a user into an admin, identified by the USERNAME environment variable'
  11. task make_admin: :environment do
  12. include RoutingHelper
  13. account_username = ENV.fetch('USERNAME')
  14. user = User.joins(:account).where(accounts: { username: account_username })
  15. if user.present?
  16. user.update(admin: true)
  17. puts "Congrats! #{account_username} is now an admin. \\o/\nNavigate to #{edit_admin_settings_url} to get started"
  18. else
  19. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  20. end
  21. end
  22. desc 'Turn a user into a moderator, identified by the USERNAME environment variable'
  23. task make_mod: :environment do
  24. account_username = ENV.fetch('USERNAME')
  25. user = User.joins(:account).where(accounts: { username: account_username })
  26. if user.present?
  27. user.update(moderator: true)
  28. puts "Congrats! #{account_username} is now a moderator \\o/"
  29. else
  30. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  31. end
  32. end
  33. desc 'Remove admin and moderator privileges from user identified by the USERNAME environment variable'
  34. task revoke_staff: :environment do
  35. account_username = ENV.fetch('USERNAME')
  36. user = User.joins(:account).where(accounts: { username: account_username })
  37. if user.present?
  38. user.update(moderator: false, admin: false)
  39. puts "#{account_username} is no longer admin or moderator."
  40. else
  41. puts "User could not be found; please make sure an account with the `#{account_username}` username exists."
  42. end
  43. end
  44. desc 'Manually confirms a user with associated user email address stored in USER_EMAIL environment variable.'
  45. task confirm_email: :environment do
  46. email = ENV.fetch('USER_EMAIL')
  47. user = User.find_by(email: email)
  48. if user
  49. user.update(confirmed_at: Time.now.utc)
  50. puts "#{email} confirmed"
  51. else
  52. abort "#{email} not found"
  53. end
  54. end
  55. desc 'Add a user by providing their email, username and initial password.' \
  56. 'The user will receive a confirmation email, then they must reset their password before logging in.'
  57. task add_user: :environment do
  58. print 'Enter email: '
  59. email = STDIN.gets.chomp
  60. print 'Enter username: '
  61. username = STDIN.gets.chomp
  62. print 'Create user and send them confirmation mail [y/N]: '
  63. confirm = STDIN.gets.chomp
  64. puts
  65. if confirm.casecmp('y').zero?
  66. password = SecureRandom.hex
  67. user = User.new(email: email, password: password, account_attributes: { username: username })
  68. if user.save
  69. puts 'User added and confirmation mail sent to user\'s email address.'
  70. puts "Here is the random password generated for the user: #{password}"
  71. else
  72. puts 'Following errors occured while creating new user:'
  73. user.errors.each do |key, val|
  74. puts "#{key}: #{val}"
  75. end
  76. end
  77. else
  78. puts 'Aborted by user.'
  79. end
  80. puts
  81. end
  82. namespace :media do
  83. desc 'Removes media attachments that have not been assigned to any status for longer than a day (deprecated)'
  84. task clear: :environment do
  85. # No-op
  86. # This task is now executed via sidekiq-scheduler
  87. end
  88. desc 'Remove media attachments attributed to silenced accounts'
  89. task remove_silenced: :environment do
  90. MediaAttachment.where(account: Account.silenced).find_each(&:destroy)
  91. end
  92. desc 'Remove cached remote media attachments that are older than NUM_DAYS. By default 7 (week)'
  93. task remove_remote: :environment do
  94. time_ago = ENV.fetch('NUM_DAYS') { 7 }.to_i.days.ago
  95. MediaAttachment.where.not(remote_url: '').where.not(file_file_name: nil).where('created_at < ?', time_ago).find_each do |media|
  96. media.file.destroy
  97. media.save
  98. end
  99. end
  100. desc 'Set unknown attachment type for remote-only attachments'
  101. task set_unknown: :environment do
  102. puts 'Setting unknown attachment type for remote-only attachments...'
  103. MediaAttachment.where(file_file_name: nil).where.not(type: :unknown).in_batches.update_all(type: :unknown)
  104. puts 'Done!'
  105. end
  106. desc 'Redownload avatars/headers of remote users. Optionally limit to a particular domain with DOMAIN'
  107. task redownload_avatars: :environment do
  108. accounts = Account.remote
  109. accounts = accounts.where(domain: ENV['DOMAIN']) if ENV['DOMAIN'].present?
  110. accounts.find_each do |account|
  111. account.reset_avatar!
  112. account.reset_header!
  113. account.save
  114. end
  115. end
  116. end
  117. namespace :push do
  118. desc 'Unsubscribes from PuSH updates of feeds nobody follows locally'
  119. task clear: :environment do
  120. Pubsubhubbub::UnsubscribeWorker.push_bulk(Account.remote.without_followers.where.not(subscription_expires_at: nil).pluck(:id))
  121. end
  122. desc 'Re-subscribes to soon expiring PuSH subscriptions (deprecated)'
  123. task refresh: :environment do
  124. # No-op
  125. # This task is now executed via sidekiq-scheduler
  126. end
  127. end
  128. namespace :feeds do
  129. desc 'Clear timelines of inactive users (deprecated)'
  130. task clear: :environment do
  131. # No-op
  132. # This task is now executed via sidekiq-scheduler
  133. end
  134. desc 'Clear all timelines without regenerating them'
  135. task clear_all: :environment do
  136. Redis.current.keys('feed:*').each { |key| Redis.current.del(key) }
  137. end
  138. desc 'Generates home timelines for users who logged in in the past two weeks'
  139. task build: :environment do
  140. User.active.includes(:account).find_each do |u|
  141. PrecomputeFeedService.new.call(u.account)
  142. end
  143. end
  144. end
  145. namespace :emails do
  146. desc 'Send out digest e-mails (deprecated)'
  147. task digest: :environment do
  148. # No-op
  149. # This task is now executed via sidekiq-scheduler
  150. end
  151. end
  152. namespace :users do
  153. desc 'Clear out unconfirmed users (deprecated)'
  154. task clear: :environment do
  155. # No-op
  156. # This task is now executed via sidekiq-scheduler
  157. end
  158. desc 'List e-mails of all admin users'
  159. task admins: :environment do
  160. puts 'Admin user emails:'
  161. puts User.admins.map(&:email).join("\n")
  162. end
  163. end
  164. namespace :settings do
  165. desc 'Open registrations on this instance'
  166. task open_registrations: :environment do
  167. Setting.open_registrations = true
  168. end
  169. desc 'Close registrations on this instance'
  170. task close_registrations: :environment do
  171. Setting.open_registrations = false
  172. end
  173. end
  174. namespace :webpush do
  175. desc 'Generate VAPID key'
  176. task generate_vapid_key: :environment do
  177. vapid_key = Webpush.generate_key
  178. puts "VAPID_PRIVATE_KEY=#{vapid_key.private_key}"
  179. puts "VAPID_PUBLIC_KEY=#{vapid_key.public_key}"
  180. end
  181. end
  182. namespace :maintenance do
  183. desc 'Update counter caches'
  184. task update_counter_caches: :environment do
  185. puts 'Updating counter caches for accounts...'
  186. Account.unscoped.where.not(protocol: :activitypub).select('id').find_in_batches do |batch|
  187. 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)')
  188. end
  189. puts 'Updating counter caches for statuses...'
  190. Status.unscoped.select('id').find_in_batches do |batch|
  191. 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)')
  192. end
  193. puts 'Done!'
  194. end
  195. desc 'Generate static versions of GIF avatars/headers'
  196. task add_static_avatars: :environment do
  197. puts 'Generating static avatars/headers for GIF ones...'
  198. Account.unscoped.where(avatar_content_type: 'image/gif').or(Account.unscoped.where(header_content_type: 'image/gif')).find_each do |account|
  199. begin
  200. account.avatar.reprocess! if account.avatar_content_type == 'image/gif' && !account.avatar.exists?(:static)
  201. account.header.reprocess! if account.header_content_type == 'image/gif' && !account.header.exists?(:static)
  202. rescue StandardError => e
  203. Rails.logger.error "Error while generating static avatars/headers for account #{account.id}: #{e}"
  204. next
  205. end
  206. end
  207. puts 'Done!'
  208. end
  209. desc 'Ensure referencial integrity'
  210. task prepare_for_foreign_keys: :environment do
  211. # All the deletes:
  212. 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')
  213. if ActiveRecord::Base.connection.table_exists? :account_domain_blocks
  214. 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')
  215. end
  216. if ActiveRecord::Base.connection.table_exists? :conversation_mutes
  217. 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')
  218. 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')
  219. end
  220. 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')
  221. 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')
  222. 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')
  223. 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')
  224. 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')
  225. 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')
  226. 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')
  227. 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')
  228. 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')
  229. 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')
  230. 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')
  231. 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')
  232. 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')
  233. 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')
  234. 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')
  235. 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')
  236. 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')
  237. 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')
  238. 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')
  239. 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')
  240. 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')
  241. 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')
  242. 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')
  243. 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')
  244. 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')
  245. 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')
  246. 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')
  247. 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')
  248. # All the nullifies:
  249. 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')
  250. 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')
  251. 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')
  252. 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')
  253. 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')
  254. end
  255. desc 'Remove deprecated preview cards'
  256. task remove_deprecated_preview_cards: :environment do
  257. next unless ActiveRecord::Base.connection.table_exists? 'deprecated_preview_cards'
  258. class DeprecatedPreviewCard < ActiveRecord::Base
  259. self.inheritance_column = false
  260. path = '/preview_cards/:attachment/:id_partition/:style/:filename'
  261. if ENV['S3_ENABLED'] != 'true'
  262. path = (ENV['PAPERCLIP_ROOT_PATH'] || ':rails_root/public/system') + path
  263. end
  264. has_attached_file :image, styles: { original: '280x120>' }, convert_options: { all: '-quality 80 -strip' }, path: path
  265. end
  266. puts 'Delete records and associated files from deprecated preview cards? [y/N]: '
  267. confirm = STDIN.gets.chomp
  268. if confirm.casecmp('y').zero?
  269. DeprecatedPreviewCard.in_batches.destroy_all
  270. puts 'Drop deprecated preview cards table? [y/N]: '
  271. confirm = STDIN.gets.chomp
  272. if confirm.casecmp('y').zero?
  273. ActiveRecord::Migration.drop_table :deprecated_preview_cards
  274. end
  275. end
  276. end
  277. desc 'Migrate photo preview cards made before 2.1'
  278. task migrate_photo_preview_cards: :environment do
  279. status_ids = Status.joins(:preview_cards)
  280. .where(preview_cards: { embed_url: '', type: :photo })
  281. .reorder(nil)
  282. .group(:id)
  283. .pluck(:id)
  284. PreviewCard.where(embed_url: '', type: :photo).delete_all
  285. LinkCrawlWorker.push_bulk status_ids
  286. end
  287. desc 'Check every known remote account and delete those that no longer exist in origin'
  288. task purge_removed_accounts: :environment do
  289. prepare_for_options!
  290. options = {}
  291. OptionParser.new do |opts|
  292. opts.banner = 'Usage: rails mastodon:maintenance:purge_removed_accounts [options]'
  293. opts.on('-f', '--force', 'Remove all encountered accounts without asking for confirmation') do
  294. options[:force] = true
  295. end
  296. opts.on('-h', '--help', 'Display this message') do
  297. puts opts
  298. exit
  299. end
  300. end.parse!
  301. disable_log_stdout!
  302. total = Account.remote.where(protocol: :activitypub).count
  303. progress_bar = ProgressBar.create(total: total, format: '%c/%C |%w>%i| %e')
  304. Account.remote.where(protocol: :activitypub).partitioned.find_each do |account|
  305. progress_bar.increment
  306. begin
  307. res = Request.new(:head, account.uri).perform
  308. rescue StandardError
  309. # This could happen due to network timeout, DNS timeout, wrong SSL cert, etc,
  310. # which should probably not lead to perceiving the account as deleted, so
  311. # just skip till next time
  312. next
  313. end
  314. if [404, 410].include?(res.code)
  315. if options[:force]
  316. account.destroy
  317. else
  318. progress_bar.pause
  319. progress_bar.clear
  320. print "\nIt seems like #{account.acct} no longer exists. Purge the account from the database? [Y/n]: ".colorize(:yellow)
  321. confirm = STDIN.gets.chomp
  322. puts ''
  323. progress_bar.resume
  324. if confirm.casecmp('n').zero?
  325. next
  326. else
  327. account.destroy
  328. end
  329. end
  330. end
  331. end
  332. end
  333. end
  334. end
  335. def disable_log_stdout!
  336. dev_null = Logger.new('/dev/null')
  337. Rails.logger = dev_null
  338. ActiveRecord::Base.logger = dev_null
  339. HttpLog.configuration.logger = dev_null
  340. Paperclip.options[:log] = false
  341. end
  342. def prepare_for_options!
  343. 2.times { ARGV.shift }
  344. end