emoji_cli.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. # rubocop:disable Rails/Output
  7. module Mastodon
  8. class EmojiCLI < Thor
  9. option :prefix
  10. option :suffix
  11. option :overwrite, type: :boolean
  12. option :unlisted, type: :boolean
  13. desc 'import PATH', 'Import emoji from a TAR archive at PATH'
  14. long_desc <<-LONG_DESC
  15. Imports custom emoji from a TAR archive specified by PATH.
  16. Existing emoji will be skipped unless the --overwrite option
  17. is provided, in which case they will be overwritten.
  18. With the --prefix option, a prefix can be added to all
  19. generated shortcodes. Likewise, the --suffix option controls
  20. the suffix of all shortcodes.
  21. With the --unlisted option, the processed emoji will not be
  22. visible in the emoji picker (but still usable via other means)
  23. LONG_DESC
  24. def import(path)
  25. imported = 0
  26. skipped = 0
  27. failed = 0
  28. Gem::Package::TarReader.new(Zlib::GzipReader.open(path)) do |tar|
  29. tar.each do |entry|
  30. next unless entry.file? && entry.full_name.end_with?('.png')
  31. shortcode = [options[:prefix], File.basename(entry.full_name, '.*'), options[:suffix]].compact.join
  32. custom_emoji = CustomEmoji.local.find_by(shortcode: shortcode)
  33. if custom_emoji && !options[:overwrite]
  34. skipped += 1
  35. next
  36. end
  37. custom_emoji ||= CustomEmoji.new(shortcode: shortcode, domain: nil)
  38. custom_emoji.image = StringIO.new(entry.read)
  39. custom_emoji.image_file_name = File.basename(entry.full_name)
  40. custom_emoji.visible_in_picker = !options[:unlisted]
  41. if custom_emoji.save
  42. imported += 1
  43. else
  44. failed += 1
  45. say('Failure/Error: ', :red)
  46. say(entry.full_name)
  47. say(' ' + custom_emoji.errors[:image].join(', '), :red)
  48. end
  49. end
  50. end
  51. puts
  52. say("Imported #{imported}, skipped #{skipped}, failed to import #{failed}", color(imported, skipped, failed))
  53. end
  54. private
  55. def color(green, _yellow, red)
  56. if !green.zero? && red.zero?
  57. :green
  58. elsif red.zero?
  59. :yellow
  60. else
  61. :red
  62. end
  63. end
  64. end
  65. end
  66. # rubocop:enable Rails/Output