process.py 2.29 KB
import ipdb
import os
from services import serviceFactory
from database import DBconnection
from enums import Services, States, Datatypes, Table

class Process:

  def __init__(self,db):
    self.db = db
    self.conn = DBconnection(db)

  # stores the message and returns its id
  def store(self,query):
    # service is wrong
    if not Services.validate(query[Table.serv]):
      return "No existe el servicio '" + query[Table.serv] + "'"
    # message can't be sent by this service
    if not serviceFactory(query[Table.serv]).validate(query[Table.type]):
      return "El servicio '" + query[Table.serv] + "' no puede enviar el tipo '" + query[Table.type] + "'"
    entities = {
      Table.path : query[Table.path],
      Table.file : query[Table.file],
      Table.dest : query[Table.dest],
      Table.serv : query[Table.serv],
      Table.type : query[Table.type],
      Table.state : States.queued
    }
    id = self.conn.insert("msg",entities)
    return id

  # tries to send all messages available
  def send(self):
    rows = self.conn.query("SELECT * FROM msg WHERE state = ?",(States.queued,))
    for query in DBconnection.parseToTable(rows):
      # if file doesn't exist, erase the message request, it can't be read anyway
      if not os.path.exists(query[Table.path]):
        self.conn.query("DELETE FROM msg WHERE id = ?",(query[Table.id],))
        continue
      serv = serviceFactory(query[Table.serv])
      success = serv.send(query)
      if success:
        # save as delivered
        self.conn.query("UPDATE msg SET state = ? WHERE id = ?",(States.delivered,query[Table.id]))

  # returns the state of a message given its id
  # stores the message to history if delivered
  def lookup(self,id):
    rows = self.conn.query("SELECT * FROM msg WHERE id = ?",(id,))
    if rows == []:
      return "El id " + str(id) + " no existe"
    rows = DBconnection.parseToTable(rows)
    row = rows[0]
    if row[Table.state] == States.delivered:
      self.conn.query("DELETE FROM msg WHERE id = ?",(id,))
      entities = {
        Table.path : row[Table.path],
        Table.file : row[Table.file],
        Table.serv : row[Table.serv],
        Table.dest : row[Table.dest],
        Table.type : row[Table.type],
        Table.state : row[Table.state],
      }
      self.conn.insert("history",entities)
    return row