# encoding: utf-8 require 'singleton' require 'sucker_punch' class MailSender include SuckerPunch::Job attr_reader :access_token, :expire, :refresh_token def _do_connect(uri, form={},token=nil) url = URI.parse("#{uri}") http = Net::HTTP.new(url.host, url.port) http.read_timeout = 1000 http.use_ssl = (url.scheme == 'https') http.verify_mode = OpenSSL::SSL::VERIFY_NONE header = { 'Content-Type' => 'application/x-www-form-urlencoded' } header["Authorization"] = "Bearer #{token}" unless token.nil? request = Net::HTTP::Post.new(url, header) request.form_data = form http.start { |http| http.request(request) } end def _authorize_mail params = [ [ "grant_type", "password" ], [ "client_id", "MailApp" ], [ "client_secret", "MailAppPRD2018!" ] ] retry_times = 0 begin response = _do_connect("https://comunicacion.hexacta.com:4443/apptoken",params) rescue StandardError => bang response = nil end until response.is_a?( Net::HTTPSuccess ) || retry_times > 10 do begin retry_times = retry_times + 1 sleep(retry_times) response = _do_connect("https://comunicacion.hexacta.com:4443/apptoken",params) rescue StandardError => bang end end if( response.is_a?( Net::HTTPSuccess ) ) token = JSON.parse(response.body) @access_token = token["access_token"] @refresh_token = token["refresh_token"] @expire = DateTime.parse(token[".expires"]) return true else NotificationSender.instance.send_error(nil,'Authorize mail failed',response.body) return false end end def _build_map_values(mail_values) values = [] for key in mail_values.keys index = mail_values.keys.index(key) values << ["MailValues[#{index}].Key", key] values << ["MailValues[#{index}].Value", mail_values[key]] end values end def _build_to_map(to_map) values = [] for key in to_map.keys index = to_map.keys.index(key) values << ["ResourcesRequest[#{index}].TypeGroup", to_map[key]] values << ["ResourcesRequest[#{index}].Name", key] end values end def _expired? @expire.nil? || DateTime.now < @expire end def do_send(mail) authorized = _expired?? _authorize_mail : true if authorized params = [ [ "ApplicationCode", 2009 ], [ "Name", mail.template ], [ "Subject", mail.subject ], [ "EmailAddress", mail.from ] ] params = params + _build_map_values(mail.values) + _build_to_map(mail.to) retry_times = 0 begin response = _do_connect("https://comunicacion.hexacta.com:4444/api/app/TemplateNotification/SendMail",params,@access_token) rescue StandardError => bang response = nil end until response.is_a?( Net::HTTPSuccess ) || retry_times > 10 do begin retry_times = retry_times + 1 sleep(retry_times) response = _do_connect("https://comunicacion.hexacta.com:4444/api/app/TemplateNotification/SendMail",params,@access_token) rescue StandardError => bang end end if( !response.is_a?( Net::HTTPSuccess ) ) NotificationSender.instance.send_error(nil,'Send mail failed',response.body) end end end def send(mail) run(mail) #Async call end #For async method call def perform(mail) do_send(mail) end end