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.

mattermost_client.rb 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. require 'dotenv/load'
  2. require 'httparty'
  3. require 'json'
  4. module SlackMattermostEmoji
  5. class MattermostClient
  6. def initialize(username:, password:, domain:, emoji_path: nil, headless: true, log: true)
  7. @username = username
  8. @password = password
  9. @domain = domain
  10. @emoji_path = File.expand_path(emoji_path || './slack-emoji')
  11. @user_id = nil
  12. @token = nil
  13. @log = log
  14. if [@username, @password, @domain].any? { |el| el.nil? || el.empty? }
  15. raise 'Mattermost username, password, and domain are all required'
  16. end
  17. end
  18. def authenticate
  19. url = "https://#{@domain}/api/v4/users/login"
  20. response = HTTParty.post(url, {
  21. body: JSON.generate({
  22. login_id: @username,
  23. password: @password,
  24. }),
  25. headers: {
  26. 'Content-Type' => 'application/json',
  27. }
  28. })
  29. raise 'Invalid Mattermost credentials' if response.code == 401
  30. user = JSON.parse(response.body)
  31. @user_id = user['id']
  32. @token = response.headers['token']
  33. end
  34. def upload_emoji
  35. emoji = Dir["#{@emoji_path}/*"]
  36. emoji_count = emoji.size
  37. digits = emoji_count.to_s.size
  38. puts "Uploading #{emoji_count} emoji... to #{@domain}"
  39. emoji.each_with_index do |file_path, index|
  40. emoji_name = File.basename(file_path, '.*')
  41. index = (index + 1).to_s.rjust(digits, ' ')
  42. print "#{index}/#{emoji_count} :#{emoji_name}:... " if @log
  43. url = "https://#{@domain}/api/v4/emoji"
  44. HTTParty.post(url, {
  45. multipart: true,
  46. body: {
  47. emoji: JSON.generate({
  48. creator_id: @user_id,
  49. name: emoji_name,
  50. }),
  51. image: File.open(file_path),
  52. },
  53. headers: {
  54. 'Content-Type' => 'multipart/form-data',
  55. 'Authorization': "Bearer #{@token}",
  56. }
  57. })
  58. puts 'success' if @log
  59. end
  60. end
  61. def authenticated?
  62. !@token.nil?
  63. end
  64. end
  65. end