闭社主体 forked from https://github.com/tootsuite/mastodon
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.

93 lines
2.7 KiB

  1. # frozen_string_literal: true
  2. require 'rubygems/package'
  3. require_relative '../../config/boot'
  4. require_relative '../../config/environment'
  5. require_relative 'cli_helper'
  6. module Mastodon
  7. class EmojiCLI < Thor
  8. def self.exit_on_failure?
  9. true
  10. end
  11. option :prefix
  12. option :suffix
  13. option :overwrite, type: :boolean
  14. option :unlisted, type: :boolean
  15. option :category
  16. desc 'import PATH', 'Import emoji from a TAR GZIP archive at PATH'
  17. long_desc <<-LONG_DESC
  18. Imports custom emoji from a TAR GZIP archive specified by PATH.
  19. Existing emoji will be skipped unless the --overwrite option
  20. is provided, in which case they will be overwritten.
  21. You can specifiy a --category under which the emojis will be
  22. grouped together.
  23. With the --prefix option, a prefix can be added to all
  24. generated shortcodes. Likewise, the --suffix option controls
  25. the suffix of all shortcodes.
  26. With the --unlisted option, the processed emoji will not be
  27. visible in the emoji picker (but still usable via other means)
  28. LONG_DESC
  29. def import(path)
  30. imported = 0
  31. skipped = 0
  32. failed = 0
  33. category = options[:category] ? CustomEmojiCategory.find_or_create_by(name: options[:category]) : nil
  34. Gem::Package::TarReader.new(Zlib::GzipReader.open(path)) do |tar|
  35. tar.each do |entry|
  36. next unless entry.file? && entry.full_name.end_with?('.png')
  37. shortcode = [options[:prefix], File.basename(entry.full_name, '.*'), options[:suffix]].compact.join
  38. custom_emoji = CustomEmoji.local.find_by(shortcode: shortcode)
  39. if custom_emoji && !options[:overwrite]
  40. skipped += 1
  41. next
  42. end
  43. custom_emoji ||= CustomEmoji.new(shortcode: shortcode, domain: nil)
  44. custom_emoji.image = StringIO.new(entry.read)
  45. custom_emoji.image_file_name = File.basename(entry.full_name)
  46. custom_emoji.visible_in_picker = !options[:unlisted]
  47. custom_emoji.category = category
  48. if custom_emoji.save
  49. imported += 1
  50. else
  51. failed += 1
  52. say('Failure/Error: ', :red)
  53. say(entry.full_name)
  54. say(' ' + custom_emoji.errors[:image].join(', '), :red)
  55. end
  56. end
  57. end
  58. puts
  59. say("Imported #{imported}, skipped #{skipped}, failed to import #{failed}", color(imported, skipped, failed))
  60. end
  61. desc 'purge', 'Remove all custom emoji'
  62. def purge
  63. CustomEmoji.in_batches.destroy_all
  64. say('OK', :green)
  65. end
  66. private
  67. def color(green, _yellow, red)
  68. if !green.zero? && red.zero?
  69. :green
  70. elsif red.zero?
  71. :yellow
  72. else
  73. :red
  74. end
  75. end
  76. end
  77. end