process_message.py 3.43 KB
import sqlite3
from sqlite3 import Error
import ipdb
import os
from services import serviceFactory, Datatypes, Services

class DBconnection:

  def __init__(self,db):
    # main table
    self.db = db
    self.query("CREATE TABLE IF NOT EXISTS msg(\
    id integer PRIMARY KEY,\
    dir text,\
    serv text CHECK( serv IN ('wpp1', 'wwp2', 'telegram', 'sms') ),\
    dest text CHECK( LENGTH(dest) <= 13 ),\
    type text CHECK( type IN ('text', 'file', 'multimedia') ),\
    state text CHECK( state IN ('delivered', 'queued') ) )")
    # delivered messages that were informed
    self.query("CREATE TABLE IF NOT EXISTS history(\
    id integer PRIMARY KEY,\
    dir text,\
    serv text CHECK( serv IN ('wpp1', 'wwp2', 'telegram', 'sms') ),\
    dest text CHECK( LENGTH(dest) <= 13 ),\
    type text CHECK( type IN ('text', 'file', 'multimedia') ),\
    state text CHECK( state IN ('delivered', 'queued') ) )")

  def query(self,query,*args):
    con = sqlite3.connect(self.db)
    cursor = con.cursor()
    entities = None
    for ar in args:
      entities = ar
    if entities:
      cursor.execute(query,entities)
    else:
      cursor.execute(query)
    if query.find("INSERT") == 0:
      cursor.execute("SELECT last_insert_rowid()")
    rows = cursor.fetchall()
    con.commit()
    con.close()
    return rows

  @staticmethod
  def parseToTable(rows):
    dictarray = []
    for row in rows:
      dictarray.append(
        {
          'id' : row[0],
          'dir' : row[1],
          'serv' : row[2],
          'dest' : row[3],
          'type' : row[4],
          'state' : row[5]
        }
      )
    return dictarray

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['serv']):
      return "No existe el servicio '" + query['serv'] + "'"
    # message can't be sent by this service
    if not serviceFactory(query['serv']).validate(query['type']):
      return "El servicio '" + query['serv'] + "' no puede enviar el tipo '" + query['type'] + "'"

    entities = (query['dir'],query['serv'],query['dest'],query['type'],'queued')
    rows = self.conn.query("INSERT INTO msg(dir,serv,dest,type,state) VALUES(?,?,?,?,?)", entities)
    return str(rows[0][0])

  # tries to send all messages available
  def send(self):
    rows = self.conn.query("SELECT * FROM msg WHERE state = 'queued'")
    for query in DBconnection.parseToTable(rows):
      # if folder doesn't exists, erase the message request, it can't be read anyway
      if not os.path.exists(query['dir']):
        self.conn.query("DELETE FROM msg WHERE id = ?",(query['id'],))
      serv = serviceFactory(query['serv'])
      success = serv.send(query)
      if success:
        # save as delivered
        self.conn.query("UPDATE msg SET state = 'delivered' WHERE id = ?",(query['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['state'] == "delivered":
      self.conn.query("DELETE FROM msg WHERE id = ?",(id,))
      self.conn.query("INSERT INTO history(dir,serv,dest,type,state) VALUES(?,?,?,?,?)", (row['dir'],row['serv'],row['dest'],row['type'],row['state']))
    return row['state']