# frozen_string_literal: true require 'net/http' require 'json' class SetupUptimerobot CONTACT_GROUP_IDS = '2811620_0_0-2806053_0_0' HTTPS_MONITORING = 1 STATUS_PAUSED = 0 def initialize(args) abort('No project name given.') if args.nil? @api_key = ask_for_api_key @url = validate_url(args) end def run robot_obj = monitoring_call(:new, create_robot_params) validate_new_project(robot_obj) response = monitoring_call(:edit, edit_robot_params(robot_obj['monitor']['id'])) final_command_status(response) end private def ask_for_api_key say 'This command will configure uptimerobot for your project.' say 'Please give in the api_key for uptimerobot' ask('API-key: ') end def validate_url(args) abort('The url to be monitored was not given') if args.first.nil? abort('The url is invalid') unless args.first =~ URI::DEFAULT_PARSER.make_regexp URI.parse(args.first) end def create_robot_params { friendly_name: @url.host.downcase, url: @url.to_s, type: HTTPS_MONITORING, interval: 300, alert_contacts: CONTACT_GROUP_IDS } end def edit_robot_params(uptimerobot_monitoring_id) { id: uptimerobot_monitoring_id, status: STATUS_PAUSED } end def final_command_status(response) if response['stat'] == 'ok' say 'Successfully configured uptimerobot 🤩😎👍' say 'The status for the monitored project has paused for now...' say 'You can start it once your app is ready to go live 🤠' else say "Something went wrong during the configuration...😕. Uptimerobot returned '#{response['error']['message']}'" end end def validate_new_project(robot_obj) return if robot_obj['stat'] == 'ok' abort("An error occoured. Uptimerobot returned '#{robot_obj['error']['message']}'") end def https_request(path, params = {}) uri = URI(path) req = request_body(uri, params) Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(req) end end def request_body(uri, params) params[:api_key] = @api_key data = URI.encode_www_form params req = Net::HTTP::Post.new(uri) req.body = data req end def monitoring_call(action, params) response = https_request("https://api.uptimerobot.com/v2/#{action}Monitor", params) JSON.parse(response.body) end end