12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- require 'dotenv/load'
- require 'httparty'
- require 'json'
-
- module SlackMattermostEmoji
- class MattermostClient
- def initialize(username:, password:, domain:, emoji_path: nil, headless: true, log: true)
- @username = username
- @password = password
- @domain = domain
- @emoji_path = File.expand_path(emoji_path || './slack-emoji')
- @user_id = nil
- @token = nil
- @log = log
-
- if [@username, @password, @domain].any? { |el| el.nil? || el.empty? }
- raise 'Mattermost username, password, and domain are all required'
- end
- end
-
- def authenticate
- url = "https://#{@domain}/api/v4/users/login"
- response = HTTParty.post(url, {
- body: JSON.generate({
- login_id: @username,
- password: @password,
- }),
- headers: {
- 'Content-Type' => 'application/json',
- }
- })
-
- raise 'Invalid Mattermost credentials' if response.code == 401
-
- user = JSON.parse(response.body)
- @user_id = user['id']
- @token = response.headers['token']
- end
-
- def upload_emoji
- emoji = Dir["#{@emoji_path}/*"]
- emoji_count = emoji.size
- digits = emoji_count.to_s.size
-
- puts "Uploading #{emoji_count} emoji... to #{@domain}"
-
- emoji.each_with_index do |file_path, index|
- emoji_name = File.basename(file_path, '.*')
- index = (index + 1).to_s.rjust(digits, ' ')
- print "#{index}/#{emoji_count} :#{emoji_name}:... " if @log
-
- url = "https://#{@domain}/api/v4/emoji"
- HTTParty.post(url, {
- multipart: true,
- body: {
- emoji: JSON.generate({
- creator_id: @user_id,
- name: emoji_name,
- }),
- image: File.open(file_path),
- },
- headers: {
- 'Content-Type' => 'multipart/form-data',
- 'Authorization': "Bearer #{@token}",
- }
- })
-
- puts 'success' if @log
- end
- end
-
- def authenticated?
- !@token.nil?
- end
- end
- end
|