models.py 3.73 KB
Newer Older
1 2
# -*- encoding: utf-8 -*-

3
# Donne l'etat des job pour l'intranet
4
# Vincent Legallic, Gabriel Détraz, Charlie Jacomme
5 6 7 8

import BeautifulSoup
import re, os
import time
9
import datetime
10
import urllib2
11
import dateutil.parser
12
from intranet import settings
13
from django.db import models
14
from django import forms
15
from django.utils import timezone
16

17
URL_JOBLIST = 'https://imprimante.adm.crans.org/hp/device/JobLogReport/Index'
18 19 20
CA = '/etc/ssl/certs/cacert.org.pem'
STORE_FILE = "/intranet-dev/apps/impressions/ended_jobs.csv"
store_timeout = 30
21
store_cleanup = datetime.timedelta(days=60)
22 23 24 25


class JobsSync(models.Manager):
    def sync_jobs(self):
26
        now = time.time()
27
        # On supprime les jobs trop vieux
28
        self.filter(starttime__lte = timezone.now() - store_cleanup).delete()
29 30
        # On ne recharge que tous les store_timeout ou si la table est vide
        if self.filter(lastcheck__lte = now-store_timeout) or not self.all():
31 32 33 34 35 36
            RE_JOB_NAME = re.compile('JobLogName_')
            RE_JOB_STATUS = re.compile('JobLogStatus_')
            RE_JOB_DATE = re.compile('JobLogDate_')
            req = urllib2.urlopen(URL_JOBLIST, cafile=CA)
            doc = BeautifulSoup.BeautifulSoup(req.read())
            jobs = doc.findAll(attrs={'class': 'PrintJobTicket'})
37 38


39 40 41 42
            # Puis pour chaque job recupere de l'imprimante, on cree une entree
            for i in jobs:
                try:
                    jobname = i.find(attrs={'id': RE_JOB_NAME}).text
43 44 45
                    jid = jobname.split(":")[0]
                    result = i.find(attrs={'id': RE_JOB_STATUS}).text
                    endtime = i.find(attrs={'id': RE_JOB_DATE}).text
46
                    # On ne cree que les jobs qui n'existe pas encore
47
                    if not self.filter(jid=jid):
48
                        job = self.create()
49 50 51 52 53
                        job.format_from_name(jobname, 'username', result, endtime)
                        job.save()
                    else:
                        job = self.get(jid=jid)
                        job.valid_from_job(result, endtime)
54 55 56
                        job.save()
                except ValueError:
                    pass
57

58
# Pour les travaux finis
59 60
class Jobs(models.Model):
    jobname = models.CharField(max_length=255)
61
    login = models.CharField(max_length=50)
62
    file = models.FilePathField(max_length=255)
63 64
    endtime = models.CharField(max_length=255)
    result = models.CharField(max_length=50)
65
    lastcheck = models.CharField(max_length=50)
66 67 68
    club = models.CharField(max_length=50, blank=True)
    starttime = models.DateTimeField(auto_now_add=True)
    jid = models.IntegerField(default=0)
69 70
    prix = models.FloatField(default=0)

71 72
    objects = JobsSync()

73 74
    class Meta:
        verbose_name = 'Tache terminees'
75 76 77 78 79 80 81 82 83 84 85

    def format_from_name(self, jobname, username, result, endtime):
        self.jobname = jobname
        self.username = username
        # file fallback sur jobname par default
        self.file = "file not found, jobname = %s" % (repr(self.jobname),)
        # login fallback sur username par default
        self.login = "login not found, username = %s" % (repr(self.username),)
        self.result = result
        self.endtime = time.strftime("%F %T",
        time.strptime(endtime, "%Y/%m/%d %H:%M:%S"))
86
        self.lastcheck = time.time()
87 88 89 90 91

        try: # on essaie d'acceder a des donnes en plus si elles existent
            tab = jobname.split(':')
            self.login = tab[1].lower()
            self.file = ":".join(tab[2:])
92
            self.jid = tab[0]
93 94
        except:
            pass
95

96
    def valid_from_job(self, result, endtime):
97 98
        enddate = dateutil.parser.parse(endtime)
        self.endtime = time.strftime("%F %T", enddate.timetuple())
99 100
        self.lastcheck = time.time()
        self.result = result