class MonitorInbox include Interactor VALID_ACTIONS = [ "encender", ] def call build_authorized_senders context.actions_executed_count=0 email = context.email || ENV["EMAIL"] password = context.password || ENV["PASSWORD"] fetch_emails_res = FetchEmails.call!( email: email, password: password, query_from: calculate_from_time ) emails_arr = fetch_emails_res.messages analyze_emails(emails_arr) context.analyzed_emails_count = emails_arr.count end # Construye un array de direcciones de email a partir del contenido de la variable # de entorno AUTHORIZED_SENDERS que contendra una lista de emails separados por coma def build_authorized_senders context.authorized_senders = ENV["AUTHORIZED_SENDERS"].split(",") end # Si existe un registro de ActionLog entonces usar el created_at time # sino utilizar ahora def calculate_from_time latest_action_log = ActionLog.last time = if latest_action_log latest_action_log.created_at else Time.now - 5.minutes end time end # Analiza uno a uno los elmentos del array de emails def analyze_emails(emails_arr) emails_arr.each do |email| Rails.logger.info "Analyzing email with subject: #{email.subject} From: #{email.from} On #{email.date}" if is_action_email?(email) execute_action(email) end end end # Verifica si un email es considerado basado en su subject y quien lo envio def is_action_email?(email) VALID_ACTIONS.include?(email.subject.downcase) && context.authorized_senders.include?(email.from.downcase) end # Ejecuta la accion indicada en el email def execute_action(email) al=ActionLog.new( from: email.from, subject: email.subject, created_at: email.date, action: "encender" ) if al.valid? Rails.logger.info "Executing action..." command = ENV["COMMAND"] system(command) context.actions_executed_count+=1 al.save! else # We're using the validate uniqueness of ActionLog to detect duplicate actions # we have already processed if we get this exception we should not execute it Rails.logger.info "We have already executed this action" end end end