iro/model/job.py
author Sandro Knauß <knauss@netzguerilla.net>
Thu, 23 Feb 2012 16:59:49 +0100
branchdevel
changeset 185 8ad6c097bc5b
parent 175 c29acd5fb841
child 215 5bacdb7e94d1
permissions -rw-r--r--
config is now cleaned in tearDown

from twisted.python import log
from twisted.python import threadable

from datetime import datetime
from collections import MutableMapping

import schema
import offer
from .dbdefer import dbdefer

class ExJob:
    '''One Job is a class that handles one job. One Job has multiple tasks.'''
    
    synchronized = ["incStatus", "_status"]

    def __init__(self, dbjob, recipients, message, offers):
        self.dbjob = dbjob       #Connection to mysql job element (id)
        self.message = message
        self.recipients = recipients
        self.offers = offers
        self.tasks={}
        self.c = 0
        self.status = "started"

    def addTask(self,task):
        self.tasks[task.recipient] = task

    def incStatus(self):
        self.c += 1
        return self.c

    def _status(self, session, status):
        job = schema.Job.get(session, self.dbjob)
        if self.status == "error":
            return
        elif self.status == "sended" and status != "error":
            return
        job.status = status
        self.status = status
        session.commit()

    @dbdefer
    def setStatus(self, session, task, status):
        c = self.incStatus()
        job = schema.Job.get(session, self.dbjob)
        
        if job.status in ["started","init"]:
            self._status(session,"sending")
        if c == len(self.recipients):
            self._status(session,"sended") 

        if status.costs > 0:
            o = schema.Offer.get(session, status.provider.name, status.route, self.message.typ)
            job.messages.append(schema.Message(price=status.costs, isBilled=False, recipient=str(task.recipient), date=datetime.today(), offer=o))
        session.commit()
        
        log.msg("Job(%s) to '%s' ended sucecessfully via %s:%s."%(self.dbjob, task.recipient, status.provider.name,status.route))

    @dbdefer
    def setError(self, session, task, err):
        self.incStatus()
        if self.status != "error":
            self._status(session,"error")

        log.err(_why="Error: Job(%s) to '%s' failed."%(self.dbjob, task.recipient),_stuff=err)

threadable.synchronize(ExJob)

class ExJobs(dict, MutableMapping):

    @dbdefer
    def create(self, session, user, recipients, message, offers, info=None):
        user = session.merge(user)
        job = schema.Job(info=info, status="started")
        user.jobs.append(job)
        session.commit()
        
        o = offer.extendProvider(user, message.typ, offers, session=session)
        self[job.id] = ExJob(job.id, recipients, message, o)
        return self[job.id]

exJobs = ExJobs()