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.

383 lines
14 KiB

  1. # frozen_string_literal: true
  2. require_relative '../../config/boot'
  3. require_relative '../../config/environment'
  4. require_relative 'cli_helper'
  5. module Mastodon
  6. class MediaCLI < Thor
  7. include ActionView::Helpers::NumberHelper
  8. include CLIHelper
  9. def self.exit_on_failure?
  10. true
  11. end
  12. option :days, type: :numeric, default: 7, aliases: [:d]
  13. option :prune_profiles, type: :boolean, default: false
  14. option :remove_headers, type: :boolean, default: false
  15. option :include_follows, type: :boolean, default: false
  16. option :concurrency, type: :numeric, default: 5, aliases: [:c]
  17. option :dry_run, type: :boolean, default: false
  18. desc 'remove', 'Remove remote media files, headers or avatars'
  19. long_desc <<-DESC
  20. Removes locally cached copies of media attachments (and optionally profile
  21. headers and avatars) from other servers. By default, only media attachements
  22. are removed.
  23. The --days option specifies how old media attachments have to be before
  24. they are removed. In case of avatars and headers, it specifies how old
  25. the last webfinger request and update to the user has to be before they
  26. are pruned. It defaults to 7 days.
  27. If --prune-profiles is specified, only avatars and headers are removed.
  28. If --remove-headers is specified, only headers are removed.
  29. If --include-follows is specified along with --prune-profiles or
  30. --remove-headers, all non-local profiles will be pruned irrespective of
  31. follow status. By default, only accounts that are not followed by or
  32. following anyone locally are pruned.
  33. DESC
  34. # rubocop:disable Metrics/PerceivedComplexity
  35. def remove
  36. if options[:prune_profiles] && options[:remove_headers]
  37. say('--prune-profiles and --remove-headers should not be specified simultaneously', :red, true)
  38. exit(1)
  39. end
  40. if options[:include_follows] && !(options[:prune_profiles] || options[:remove_headers])
  41. say('--include-follows can only be used with --prune-profiles or --remove-headers', :red, true)
  42. exit(1)
  43. end
  44. time_ago = options[:days].days.ago
  45. dry_run = options[:dry_run] ? ' (DRY RUN)' : ''
  46. if options[:prune_profiles] || options[:remove_headers]
  47. processed, aggregate = parallelize_with_progress(Account.remote.where({ last_webfingered_at: ..time_ago, updated_at: ..time_ago })) do |account|
  48. next if !options[:include_follows] && Follow.where(account: account).or(Follow.where(target_account: account)).exists?
  49. next if account.avatar.blank? && account.header.blank?
  50. next if options[:remove_headers] && account.header.blank?
  51. size = (account.header_file_size || 0)
  52. size += (account.avatar_file_size || 0) if options[:prune_profiles]
  53. unless options[:dry_run]
  54. account.header.destroy
  55. account.avatar.destroy if options[:prune_profiles]
  56. account.save!
  57. end
  58. size
  59. end
  60. say("Visited #{processed} accounts and removed profile media totaling #{number_to_human_size(aggregate)}#{dry_run}", :green, true)
  61. end
  62. unless options[:prune_profiles] || options[:remove_headers]
  63. processed, aggregate = parallelize_with_progress(MediaAttachment.cached.where.not(remote_url: '').where(created_at: ..time_ago)) do |media_attachment|
  64. next if media_attachment.file.blank?
  65. size = (media_attachment.file_file_size || 0) + (media_attachment.thumbnail_file_size || 0)
  66. unless options[:dry_run]
  67. media_attachment.file.destroy
  68. media_attachment.thumbnail.destroy
  69. media_attachment.save
  70. end
  71. size
  72. end
  73. say("Removed #{processed} media attachments (approx. #{number_to_human_size(aggregate)})#{dry_run}", :green, true)
  74. end
  75. end
  76. option :start_after
  77. option :prefix
  78. option :fix_permissions, type: :boolean, default: false
  79. option :dry_run, type: :boolean, default: false
  80. desc 'remove-orphans', 'Scan storage and check for files that do not belong to existing media attachments'
  81. long_desc <<~LONG_DESC
  82. Scans file storage for files that do not belong to existing media attachments. Because this operation
  83. requires iterating over every single file individually, it will be slow.
  84. Please mind that some storage providers charge for the necessary API requests to list objects.
  85. LONG_DESC
  86. def remove_orphans
  87. progress = create_progress_bar(nil)
  88. reclaimed_bytes = 0
  89. removed = 0
  90. dry_run = options[:dry_run] ? ' (DRY RUN)' : ''
  91. prefix = options[:prefix]
  92. case Paperclip::Attachment.default_options[:storage]
  93. when :s3
  94. paperclip_instance = MediaAttachment.new.file
  95. s3_interface = paperclip_instance.s3_interface
  96. s3_permissions = Paperclip::Attachment.default_options[:s3_permissions]
  97. bucket = s3_interface.bucket(Paperclip::Attachment.default_options[:s3_credentials][:bucket])
  98. last_key = options[:start_after]
  99. loop do
  100. objects = begin
  101. bucket.objects(start_after: last_key, prefix: prefix).limit(1000).map { |x| x }
  102. rescue => e
  103. progress.log(pastel.red("Error fetching list of files: #{e}"))
  104. progress.log("If you want to continue from this point, add --start-after=#{last_key} to your command") if last_key
  105. break
  106. end
  107. break if objects.empty?
  108. last_key = objects.last.key
  109. record_map = preload_records_from_mixed_objects(objects)
  110. objects.each do |object|
  111. object.acl.put(acl: s3_permissions) if options[:fix_permissions] && !options[:dry_run]
  112. path_segments = object.key.split('/')
  113. path_segments.delete('cache')
  114. unless [7, 10].include?(path_segments.size)
  115. progress.log(pastel.yellow("Unrecognized file found: #{object.key}"))
  116. next
  117. end
  118. model_name = path_segments.first.classify
  119. attachment_name = path_segments[1].singularize
  120. record_id = path_segments[2..-2].join.to_i
  121. file_name = path_segments.last
  122. record = record_map.dig(model_name, record_id)
  123. attachment = record&.public_send(attachment_name)
  124. progress.increment
  125. next unless attachment.blank? || !attachment.variant?(file_name)
  126. begin
  127. object.delete unless options[:dry_run]
  128. reclaimed_bytes += object.size
  129. removed += 1
  130. progress.log("Found and removed orphan: #{object.key}")
  131. rescue => e
  132. progress.log(pastel.red("Error processing #{object.key}: #{e}"))
  133. end
  134. end
  135. end
  136. when :fog
  137. say('The fog storage driver is not supported for this operation at this time', :red)
  138. exit(1)
  139. when :filesystem
  140. require 'find'
  141. root_path = ENV.fetch('PAPERCLIP_ROOT_PATH', File.join(':rails_root', 'public', 'system')).gsub(':rails_root', Rails.root.to_s)
  142. Find.find(File.join(*[root_path, prefix].compact)) do |path|
  143. next if File.directory?(path)
  144. key = path.gsub("#{root_path}#{File::SEPARATOR}", '')
  145. path_segments = key.split(File::SEPARATOR)
  146. path_segments.delete('cache')
  147. unless [7, 10].include?(path_segments.size)
  148. progress.log(pastel.yellow("Unrecognized file found: #{key}"))
  149. next
  150. end
  151. model_name = path_segments.first.classify
  152. record_id = path_segments[2..-2].join.to_i
  153. attachment_name = path_segments[1].singularize
  154. file_name = path_segments.last
  155. next unless PRELOAD_MODEL_WHITELIST.include?(model_name)
  156. record = model_name.constantize.find_by(id: record_id)
  157. attachment = record&.public_send(attachment_name)
  158. progress.increment
  159. next unless attachment.blank? || !attachment.variant?(file_name)
  160. begin
  161. size = File.size(path)
  162. unless options[:dry_run]
  163. File.delete(path)
  164. begin
  165. FileUtils.rmdir(File.dirname(path), parents: true)
  166. rescue Errno::ENOTEMPTY
  167. # OK
  168. end
  169. end
  170. reclaimed_bytes += size
  171. removed += 1
  172. progress.log("Found and removed orphan: #{key}")
  173. rescue => e
  174. progress.log(pastel.red("Error processing #{key}: #{e}"))
  175. end
  176. end
  177. end
  178. progress.total = progress.progress
  179. progress.finish
  180. say("Removed #{removed} orphans (approx. #{number_to_human_size(reclaimed_bytes)})#{dry_run}", :green, true)
  181. end
  182. # rubocop:enable Metrics/PerceivedComplexity
  183. option :account, type: :string
  184. option :domain, type: :string
  185. option :status, type: :numeric
  186. option :days, type: :numeric
  187. option :concurrency, type: :numeric, default: 5, aliases: [:c]
  188. option :verbose, type: :boolean, default: false, aliases: [:v]
  189. option :dry_run, type: :boolean, default: false
  190. option :force, type: :boolean, default: false
  191. desc 'refresh', 'Fetch remote media files'
  192. long_desc <<-DESC
  193. Re-downloads media attachments from other servers. You must specify the
  194. source of media attachments with one of the following options:
  195. Use the --status option to download attachments from a specific status,
  196. using the status local numeric ID.
  197. Use the --account option to download attachments from a specific account,
  198. using username@domain handle of the account.
  199. Use the --domain option to download attachments from a specific domain.
  200. Use the --days option to limit attachments created within days.
  201. By default, attachments that are believed to be already downloaded will
  202. not be re-downloaded. To force re-download of every URL, use --force.
  203. DESC
  204. def refresh
  205. dry_run = options[:dry_run] ? ' (DRY RUN)' : ''
  206. if options[:status]
  207. scope = MediaAttachment.where(status_id: options[:status])
  208. elsif options[:account]
  209. username, domain = options[:account].split('@')
  210. account = Account.find_remote(username, domain)
  211. if account.nil?
  212. say('No such account', :red)
  213. exit(1)
  214. end
  215. scope = MediaAttachment.where(account_id: account.id)
  216. elsif options[:domain]
  217. scope = MediaAttachment.joins(:account).merge(Account.by_domain_and_subdomains(options[:domain]))
  218. elsif options[:days].present?
  219. scope = MediaAttachment.remote
  220. else
  221. exit(1)
  222. end
  223. scope = scope.where('media_attachments.id > ?', Mastodon::Snowflake.id_at(options[:days].days.ago, with_random: false)) if options[:days].present?
  224. processed, aggregate = parallelize_with_progress(scope) do |media_attachment|
  225. next if media_attachment.remote_url.blank? || (!options[:force] && media_attachment.file_file_name.present?)
  226. next if DomainBlock.reject_media?(media_attachment.account.domain)
  227. unless options[:dry_run]
  228. media_attachment.reset_file!
  229. media_attachment.reset_thumbnail!
  230. media_attachment.save
  231. end
  232. media_attachment.file_file_size + (media_attachment.thumbnail_file_size || 0)
  233. end
  234. say("Downloaded #{processed} media attachments (approx. #{number_to_human_size(aggregate)})#{dry_run}", :green, true)
  235. end
  236. desc 'usage', 'Calculate disk space consumed by Mastodon'
  237. def usage
  238. say("Attachments:\t#{number_to_human_size(MediaAttachment.sum(Arel.sql('COALESCE(file_file_size, 0) + COALESCE(thumbnail_file_size, 0)')))} (#{number_to_human_size(MediaAttachment.where(account: Account.local).sum(Arel.sql('COALESCE(file_file_size, 0) + COALESCE(thumbnail_file_size, 0)')))} local)")
  239. say("Custom emoji:\t#{number_to_human_size(CustomEmoji.sum(:image_file_size))} (#{number_to_human_size(CustomEmoji.local.sum(:image_file_size))} local)")
  240. say("Preview cards:\t#{number_to_human_size(PreviewCard.sum(:image_file_size))}")
  241. say("Avatars:\t#{number_to_human_size(Account.sum(:avatar_file_size))} (#{number_to_human_size(Account.local.sum(:avatar_file_size))} local)")
  242. say("Headers:\t#{number_to_human_size(Account.sum(:header_file_size))} (#{number_to_human_size(Account.local.sum(:header_file_size))} local)")
  243. say("Backups:\t#{number_to_human_size(Backup.sum(:dump_file_size))}")
  244. say("Imports:\t#{number_to_human_size(Import.sum(:data_file_size))}")
  245. say("Settings:\t#{number_to_human_size(SiteUpload.sum(:file_file_size))}")
  246. end
  247. desc 'lookup URL', 'Lookup where media is displayed by passing a media URL'
  248. def lookup(url)
  249. path = Addressable::URI.parse(url).path
  250. path_segments = path.split('/')[2..]
  251. path_segments.delete('cache')
  252. unless [7, 10].include?(path_segments.size)
  253. say('Not a media URL', :red)
  254. exit(1)
  255. end
  256. model_name = path_segments.first.classify
  257. record_id = path_segments[2..-2].join.to_i
  258. unless PRELOAD_MODEL_WHITELIST.include?(model_name)
  259. say("Cannot find corresponding model: #{model_name}", :red)
  260. exit(1)
  261. end
  262. record = model_name.constantize.find_by(id: record_id)
  263. record = record.status if record.respond_to?(:status)
  264. unless record
  265. say('Cannot find corresponding record', :red)
  266. exit(1)
  267. end
  268. display_url = ActivityPub::TagManager.instance.url_for(record)
  269. if display_url.blank?
  270. say('No public URL for this type of record', :red)
  271. exit(1)
  272. end
  273. say(display_url, :blue)
  274. rescue Addressable::URI::InvalidURIError
  275. say('Invalid URL', :red)
  276. exit(1)
  277. end
  278. private
  279. PRELOAD_MODEL_WHITELIST = %w(
  280. Account
  281. Backup
  282. CustomEmoji
  283. Import
  284. MediaAttachment
  285. PreviewCard
  286. SiteUpload
  287. ).freeze
  288. def preload_records_from_mixed_objects(objects)
  289. preload_map = Hash.new { |hash, key| hash[key] = [] }
  290. objects.map do |object|
  291. segments = object.key.split('/')
  292. segments.delete('cache')
  293. next unless [7, 10].include?(segments.size)
  294. model_name = segments.first.classify
  295. record_id = segments[2..-2].join.to_i
  296. next unless PRELOAD_MODEL_WHITELIST.include?(model_name)
  297. preload_map[model_name] << record_id
  298. end
  299. preload_map.each_with_object({}) do |(model_name, record_ids), model_map|
  300. model_map[model_name] = model_name.constantize.where(id: record_ids).index_by(&:id)
  301. end
  302. end
  303. end
  304. end