Toot toooooooot (Bluesky-Mastodon cross-poster)
1require 'yaml' 2require_relative 'mastodon_api' 3 4class MastodonAccount 5 APP_NAME = "Tootify" 6 CONFIG_FILE = File.expand_path(File.join(__dir__, '..', 'config', 'mastodon.yml')) 7 OAUTH_SCOPES = 'read:accounts read:statuses write:media write:statuses' 8 9 def initialize 10 @config = File.exist?(CONFIG_FILE) ? YAML.load(File.read(CONFIG_FILE)) : {} 11 end 12 13 def max_alt_length 14 1500 15 end 16 17 def save_config 18 File.write(CONFIG_FILE, YAML.dump(@config)) 19 end 20 21 def oauth_login(handle) 22 instance = handle.split('@').last 23 app_response = register_oauth_app(instance) 24 25 api = MastodonAPI.new(instance) 26 27 login_url = api.generate_oauth_login_url(app_response['client_id'], OAUTH_SCOPES) 28 29 puts "Open this URL in your web browser and authorize the app:" 30 puts 31 puts login_url 32 puts 33 puts "Then, enter the received code here:" 34 puts 35 36 print ">> " 37 code = STDIN.gets.chomp 38 39 json = api.complete_oauth_login(app_response['client_id'], app_response['client_secret'], code) 40 41 api.access_token = json['access_token'] 42 info = api.account_info 43 44 @config['handle'] = handle 45 @config['access_token'] = api.access_token 46 @config['user_id'] = info['id'] 47 save_config 48 end 49 50 def register_oauth_app(instance) 51 api = MastodonAPI.new(instance) 52 api.register_oauth_app(APP_NAME, OAUTH_SCOPES) 53 end 54 55 def post_status(text, media_ids = nil, parent_id = nil) 56 instance = @config['handle'].split('@').last 57 api = MastodonAPI.new(instance, @config['access_token']) 58 api.post_status(text, media_ids, parent_id) 59 end 60 61 def upload_media(data, filename, content_type, alt = nil) 62 instance = @config['handle'].split('@').last 63 api = MastodonAPI.new(instance, @config['access_token']) 64 api.upload_media(data, filename, content_type, alt) 65 end 66end