devicehub-django/snapshot/models.py

77 lines
2.0 KiB
Python
Raw Normal View History

2024-07-18 15:21:22 +00:00
import json
2024-06-12 07:32:49 +00:00
from django.db import models
2024-07-18 15:21:22 +00:00
2024-07-15 14:23:14 +00:00
from utils.constants import STR_SM_SIZE, STR_EXTEND_SIZE
2024-07-18 15:21:22 +00:00
from snapshot.xapian import search
2024-06-12 07:32:49 +00:00
from user.models import User
2024-07-18 15:21:22 +00:00
class Snapshot:
def __init__(self, uuid):
self.uuid = uuid
self.owner = None
self.doc = None
self.created = None
self.annotations = []
2024-06-12 07:32:49 +00:00
2024-07-18 15:21:22 +00:00
self.get_owner()
self.get_time()
2024-06-12 07:32:49 +00:00
2024-07-18 15:21:22 +00:00
def get_annotations(self):
self.annotations = Annotation.objects.filter(
uuid=self.uuid
).order_by("created")
def get_owner(self):
if not self.annotations:
self.get_annotations()
a = self.annotations.first()
if a:
self.owner = a.owner
2024-06-12 07:32:49 +00:00
2024-07-18 15:21:22 +00:00
def get_doc(self):
self.doc = {}
qry = 'uuid:"{}"'.format(self.uuid)
matches = search(qry, limit=1)
if matches.size() < 0:
return
for xa in matches:
self.doc = json.loads(xa.document.get_data())
def get_time(self):
if not self.doc:
self.get_doc()
self.created = self.doc.get("endTime")
if not self.created:
self.created = self.annotations.last().created
def components(self):
return self.doc.get('components', [])
2024-07-01 10:17:23 +00:00
2024-07-15 14:23:14 +00:00
class Annotation(models.Model):
2024-07-18 15:21:22 +00:00
class Type(models.IntegerChoices):
SYSTEM= 0, "System"
USER = 1, "User"
2024-07-15 14:23:14 +00:00
created = models.DateTimeField(auto_now_add=True)
2024-07-18 15:21:22 +00:00
uuid = models.UUIDField()
2024-07-15 14:23:14 +00:00
owner = models.ForeignKey(User, on_delete=models.CASCADE)
2024-07-18 15:21:22 +00:00
type = models.SmallIntegerField(choices=Type)
2024-07-15 14:23:14 +00:00
key = models.CharField(max_length=STR_EXTEND_SIZE)
value = models.CharField(max_length=STR_EXTEND_SIZE)
2024-07-18 15:21:22 +00:00
device = models.ForeignKey('device.Device', on_delete=models.CASCADE)
2024-07-15 14:23:14 +00:00
2024-07-18 15:21:22 +00:00
class Meta:
constraints = [
models.UniqueConstraint(fields=["type", "key", "uuid"], name="unique_type_key_uuid")
]
def is_user_annotation(self):
if self.type == self.Type.USER:
return True
return False