You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
273 lines
9.6 KiB
Python
273 lines
9.6 KiB
Python
5 years ago
|
# Copyright © 2017 Tom Hacohen
|
||
|
#
|
||
|
# This program is free software: you can redistribute it and/or modify
|
||
|
# it under the terms of the GNU Affero General Public License as
|
||
|
# published by the Free Software Foundation, version 3.
|
||
|
#
|
||
|
# This library is distributed in the hope that it will be useful,
|
||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
|
# GNU General Public License for more details.
|
||
|
#
|
||
|
# You should have received a copy of the GNU General Public License
|
||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||
|
|
||
4 years ago
|
import typing as t
|
||
5 years ago
|
from pathlib import Path
|
||
|
|
||
5 years ago
|
from django.db import models, transaction
|
||
5 years ago
|
from django.conf import settings
|
||
|
from django.core.validators import RegexValidator
|
||
4 years ago
|
from django.db.models import Max, Value as V
|
||
|
from django.db.models.functions import Coalesce, Greatest
|
||
5 years ago
|
from django.utils.functional import cached_property
|
||
5 years ago
|
from django.utils.crypto import get_random_string
|
||
5 years ago
|
|
||
4 years ago
|
from . import app_settings
|
||
|
|
||
5 years ago
|
|
||
4 years ago
|
UidValidator = RegexValidator(regex=r"^[a-zA-Z0-9\-_]{20,}$", message="Not a valid UID")
|
||
5 years ago
|
|
||
|
|
||
4 years ago
|
def stoken_annotation_builder(stoken_id_fields: t.List[str]):
|
||
4 years ago
|
aggr_fields = [Coalesce(Max(field), V(0)) for field in stoken_id_fields]
|
||
|
return Greatest(*aggr_fields) if len(aggr_fields) > 1 else aggr_fields[0]
|
||
|
|
||
|
|
||
4 years ago
|
class CollectionType(models.Model):
|
||
|
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||
4 years ago
|
uid = models.BinaryField(editable=True, blank=False, null=False, db_index=True, unique=True, max_length=1024)
|
||
4 years ago
|
|
||
4 years ago
|
objects: models.manager.BaseManager["CollectionType"]
|
||
|
|
||
4 years ago
|
|
||
5 years ago
|
class Collection(models.Model):
|
||
4 years ago
|
main_item = models.OneToOneField("CollectionItem", related_name="parent", null=True, on_delete=models.SET_NULL)
|
||
4 years ago
|
# The same as main_item.uid, we just also save it here so we have DB constraints for uniqueness (and efficiency)
|
||
|
uid = models.CharField(db_index=True, unique=True, blank=False, max_length=43, validators=[UidValidator])
|
||
5 years ago
|
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||
|
|
||
4 years ago
|
stoken_annotation = stoken_annotation_builder(["items__revisions__stoken", "members__stoken"])
|
||
4 years ago
|
|
||
4 years ago
|
objects: models.manager.BaseManager["Collection"]
|
||
|
|
||
5 years ago
|
def __str__(self):
|
||
|
return self.uid
|
||
|
|
||
5 years ago
|
@property
|
||
4 years ago
|
def content(self) -> "CollectionItemRevision":
|
||
4 years ago
|
assert self.main_item is not None
|
||
5 years ago
|
return self.main_item.content
|
||
5 years ago
|
|
||
5 years ago
|
@property
|
||
4 years ago
|
def etag(self) -> str:
|
||
5 years ago
|
return self.content.uid
|
||
5 years ago
|
|
||
|
@cached_property
|
||
4 years ago
|
def stoken(self) -> str:
|
||
4 years ago
|
stoken_id = (
|
||
|
self.__class__.objects.filter(main_item=self.main_item)
|
||
4 years ago
|
.annotate(max_stoken=self.stoken_annotation)
|
||
4 years ago
|
.values("max_stoken")
|
||
|
.first()["max_stoken"]
|
||
|
)
|
||
|
|
||
4 years ago
|
if stoken_id == 0:
|
||
4 years ago
|
raise Exception("stoken is None. Should never happen")
|
||
5 years ago
|
|
||
4 years ago
|
return Stoken.objects.get(id=stoken_id).uid
|
||
5 years ago
|
|
||
5 years ago
|
|
||
5 years ago
|
class CollectionItem(models.Model):
|
||
4 years ago
|
uid = models.CharField(db_index=True, blank=False, max_length=43, validators=[UidValidator])
|
||
|
collection = models.ForeignKey(Collection, related_name="items", on_delete=models.CASCADE)
|
||
5 years ago
|
version = models.PositiveSmallIntegerField()
|
||
5 years ago
|
encryptionKey = models.BinaryField(editable=True, blank=False, null=True)
|
||
5 years ago
|
|
||
4 years ago
|
stoken_annotation = stoken_annotation_builder(["revisions__stoken"])
|
||
|
|
||
4 years ago
|
objects: models.manager.BaseManager["CollectionItem"]
|
||
|
|
||
5 years ago
|
class Meta:
|
||
4 years ago
|
unique_together = ("uid", "collection")
|
||
5 years ago
|
|
||
|
def __str__(self):
|
||
4 years ago
|
return "{} {}".format(self.uid, self.collection.uid)
|
||
5 years ago
|
|
||
5 years ago
|
@cached_property
|
||
4 years ago
|
def content(self) -> "CollectionItemRevision":
|
||
5 years ago
|
return self.revisions.get(current=True)
|
||
5 years ago
|
|
||
5 years ago
|
@property
|
||
4 years ago
|
def etag(self) -> str:
|
||
5 years ago
|
return self.content.uid
|
||
5 years ago
|
|
||
5 years ago
|
|
||
4 years ago
|
def chunk_directory_path(instance: "CollectionItemChunk", filename: str) -> Path:
|
||
4 years ago
|
custom_func = app_settings.CHUNK_PATH_FUNC
|
||
|
if custom_func is not None:
|
||
|
return custom_func(instance, filename)
|
||
|
|
||
4 years ago
|
col: Collection = instance.collection
|
||
|
user_id: int = col.owner.id
|
||
|
uid_prefix: str = instance.uid[:2]
|
||
|
uid_rest: str = instance.uid[2:]
|
||
4 years ago
|
return Path("user_{}".format(user_id), col.uid, uid_prefix, uid_rest)
|
||
5 years ago
|
|
||
|
|
||
5 years ago
|
class CollectionItemChunk(models.Model):
|
||
4 years ago
|
uid = models.CharField(db_index=True, blank=False, null=False, max_length=60, validators=[UidValidator])
|
||
|
collection = models.ForeignKey(Collection, related_name="chunks", on_delete=models.CASCADE)
|
||
5 years ago
|
chunkFile = models.FileField(upload_to=chunk_directory_path, max_length=150, unique=True)
|
||
5 years ago
|
|
||
4 years ago
|
objects: models.manager.BaseManager["CollectionItemChunk"]
|
||
|
|
||
5 years ago
|
def __str__(self):
|
||
|
return self.uid
|
||
5 years ago
|
|
||
4 years ago
|
class Meta:
|
||
4 years ago
|
unique_together = ("collection", "uid")
|
||
4 years ago
|
|
||
5 years ago
|
|
||
5 years ago
|
def generate_stoken_uid():
|
||
4 years ago
|
return get_random_string(32, allowed_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
|
||
5 years ago
|
|
||
|
|
||
|
class Stoken(models.Model):
|
||
4 years ago
|
id: int
|
||
4 years ago
|
uid = models.CharField(
|
||
|
db_index=True,
|
||
|
unique=True,
|
||
|
blank=False,
|
||
|
null=False,
|
||
|
default=generate_stoken_uid,
|
||
|
max_length=43,
|
||
|
validators=[UidValidator],
|
||
|
)
|
||
5 years ago
|
|
||
4 years ago
|
objects: models.manager.BaseManager["Stoken"]
|
||
|
|
||
5 years ago
|
|
||
5 years ago
|
class CollectionItemRevision(models.Model):
|
||
5 years ago
|
stoken = models.OneToOneField(Stoken, on_delete=models.PROTECT)
|
||
4 years ago
|
uid = models.CharField(
|
||
|
db_index=True, unique=True, blank=False, null=False, max_length=43, validators=[UidValidator]
|
||
|
)
|
||
|
item = models.ForeignKey(CollectionItem, related_name="revisions", on_delete=models.CASCADE)
|
||
5 years ago
|
meta = models.BinaryField(editable=True, blank=False, null=False)
|
||
5 years ago
|
current = models.BooleanField(db_index=True, default=True, null=True)
|
||
5 years ago
|
deleted = models.BooleanField(default=False)
|
||
5 years ago
|
|
||
4 years ago
|
objects: models.manager.BaseManager["CollectionItemRevision"]
|
||
|
|
||
5 years ago
|
class Meta:
|
||
4 years ago
|
unique_together = ("item", "current")
|
||
5 years ago
|
|
||
|
def __str__(self):
|
||
4 years ago
|
return "{} {} current={}".format(self.uid, self.item.uid, self.current)
|
||
5 years ago
|
|
||
|
|
||
5 years ago
|
class RevisionChunkRelation(models.Model):
|
||
4 years ago
|
chunk = models.ForeignKey(CollectionItemChunk, related_name="revisions_relation", on_delete=models.CASCADE)
|
||
|
revision = models.ForeignKey(CollectionItemRevision, related_name="chunks_relation", on_delete=models.CASCADE)
|
||
5 years ago
|
|
||
4 years ago
|
objects: models.manager.BaseManager["RevisionChunkRelation"]
|
||
|
|
||
5 years ago
|
class Meta:
|
||
4 years ago
|
ordering = ("id",)
|
||
5 years ago
|
|
||
|
|
||
4 years ago
|
class AccessLevels(models.IntegerChoices):
|
||
|
READ_ONLY = 0
|
||
|
ADMIN = 1
|
||
|
READ_WRITE = 2
|
||
5 years ago
|
|
||
5 years ago
|
|
||
5 years ago
|
class CollectionMember(models.Model):
|
||
5 years ago
|
stoken = models.OneToOneField(Stoken, on_delete=models.PROTECT, null=True)
|
||
4 years ago
|
collection = models.ForeignKey(Collection, related_name="members", on_delete=models.CASCADE)
|
||
5 years ago
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||
|
encryptionKey = models.BinaryField(editable=True, blank=False, null=False)
|
||
4 years ago
|
collectionType = models.ForeignKey(CollectionType, on_delete=models.PROTECT, null=True)
|
||
4 years ago
|
accessLevel = models.IntegerField(
|
||
|
choices=AccessLevels.choices,
|
||
|
default=AccessLevels.READ_ONLY,
|
||
|
)
|
||
5 years ago
|
|
||
4 years ago
|
stoken_annotation = stoken_annotation_builder(["stoken"])
|
||
|
|
||
4 years ago
|
objects: models.manager.BaseManager["CollectionMember"]
|
||
|
|
||
5 years ago
|
class Meta:
|
||
4 years ago
|
unique_together = ("user", "collection")
|
||
5 years ago
|
|
||
|
def __str__(self):
|
||
4 years ago
|
return "{} {}".format(self.collection.uid, self.user)
|
||
5 years ago
|
|
||
5 years ago
|
def revoke(self):
|
||
|
with transaction.atomic():
|
||
|
CollectionMemberRemoved.objects.update_or_create(
|
||
4 years ago
|
collection=self.collection,
|
||
|
user=self.user,
|
||
|
defaults={
|
||
|
"stoken": Stoken.objects.create(),
|
||
|
},
|
||
5 years ago
|
)
|
||
|
|
||
|
self.delete()
|
||
|
|
||
|
|
||
|
class CollectionMemberRemoved(models.Model):
|
||
|
stoken = models.OneToOneField(Stoken, on_delete=models.PROTECT, null=True)
|
||
4 years ago
|
collection = models.ForeignKey(Collection, related_name="removed_members", on_delete=models.CASCADE)
|
||
5 years ago
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||
|
|
||
4 years ago
|
objects: models.manager.BaseManager["CollectionMemberRemoved"]
|
||
|
|
||
5 years ago
|
class Meta:
|
||
4 years ago
|
unique_together = ("user", "collection")
|
||
5 years ago
|
|
||
|
def __str__(self):
|
||
4 years ago
|
return "{} {}".format(self.collection.uid, self.user)
|
||
5 years ago
|
|
||
5 years ago
|
|
||
5 years ago
|
class CollectionInvitation(models.Model):
|
||
4 years ago
|
uid = models.CharField(db_index=True, blank=False, null=False, max_length=43, validators=[UidValidator])
|
||
5 years ago
|
version = models.PositiveSmallIntegerField(default=1)
|
||
|
fromMember = models.ForeignKey(CollectionMember, on_delete=models.CASCADE)
|
||
|
# FIXME: make sure to delete all invitations for the same collection once one is accepted
|
||
5 years ago
|
# Make sure to not allow invitations if already a member
|
||
5 years ago
|
|
||
4 years ago
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="incoming_invitations", on_delete=models.CASCADE)
|
||
5 years ago
|
signedEncryptionKey = models.BinaryField(editable=False, blank=False, null=False)
|
||
4 years ago
|
accessLevel = models.IntegerField(
|
||
|
choices=AccessLevels.choices,
|
||
|
default=AccessLevels.READ_ONLY,
|
||
|
)
|
||
5 years ago
|
|
||
4 years ago
|
objects: models.manager.BaseManager["CollectionInvitation"]
|
||
|
|
||
5 years ago
|
class Meta:
|
||
4 years ago
|
unique_together = ("user", "fromMember")
|
||
5 years ago
|
|
||
|
def __str__(self):
|
||
4 years ago
|
return "{} {}".format(self.fromMember.collection.uid, self.user)
|
||
5 years ago
|
|
||
5 years ago
|
@cached_property
|
||
4 years ago
|
def collection(self) -> Collection:
|
||
5 years ago
|
return self.fromMember.collection
|
||
|
|
||
5 years ago
|
|
||
5 years ago
|
class UserInfo(models.Model):
|
||
|
owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
|
||
|
version = models.PositiveSmallIntegerField(default=1)
|
||
5 years ago
|
loginPubkey = models.BinaryField(editable=True, blank=False, null=False)
|
||
5 years ago
|
pubkey = models.BinaryField(editable=True, blank=False, null=False)
|
||
5 years ago
|
encryptedContent = models.BinaryField(editable=True, blank=False, null=False)
|
||
5 years ago
|
salt = models.BinaryField(editable=True, blank=False, null=False)
|
||
|
|
||
4 years ago
|
objects: models.manager.BaseManager["UserInfo"]
|
||
|
|
||
5 years ago
|
def __str__(self):
|
||
|
return "UserInfo<{}>".format(self.owner)
|