emoji_cli.rb 2.3 KB

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