process.py 2.84 KB
import ipdb
import os
import json
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 data
  def datastore(self,path):
    entities = {
      Table.path : path,
      Table.state : States.preprocess
    }
    id = self.conn.insert("msg",entities)
    return id

  # stores the parameters
  def paramstore(self,query):
    # service is wrong
    if not Services.validate(query[Table.serv]):
      return "No existe el servicio '" + query[Table.serv] + "'"
    ipdb.set_trace()
    types = json.loads(query[Table.type])
    filelist = os.listdir(
      self.lookup(
        query[Table.id]
      )[Table.path]
    )
    for file in types:
      # files don't exist
      if file not in filelist:
        return "El archivo '" + file "' no existe"
      # message can't be sent by this service
      elif not serviceFactory(query[Table.serv]).validate(types[file]):
        return "El servicio '" + query[Table.serv] + "' no puede enviar el tipo '" + types[file] + "' destinado al archivo '" file "'" 
    
    entities = {
      Table.dest : query[Table.dest],
      Table.serv : query[Table.serv],
      Table.type : query[Table.type],
      Table.state : States.queued
    }
    self.conn.update("msg",(Table.id,query[Table.id]),entities)
    return States.queued

  # 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 folder doesn't exist, erase the message request
      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.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

  def paths(self):
    rows = self.conn.query("SELECT path FROM msg")
    paths = []
    for row in rows:
      paths.append(row[0])
    return paths