Aplicacion que monitorea una inbox de outlook/hotmail a traves de IMAP y cuando detecta un email con cierto subject y viniendo de una coleccion de direcciones de email conocidas, ejecuta una accion, por ejemplo: encender el server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

79 lines
2.2 KiB

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|
puts "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?
puts "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
puts "We have already executed this action"
end
end
end