2020-12-27 16:54:06 +00:00
|
|
|
import dataclasses
|
|
|
|
import typing as t
|
2020-12-28 11:56:53 +00:00
|
|
|
import msgpack
|
2020-12-28 12:26:44 +00:00
|
|
|
import base64
|
2020-12-27 16:54:06 +00:00
|
|
|
|
2020-12-28 10:12:00 +00:00
|
|
|
from fastapi import status, Query, Depends
|
2020-12-28 07:25:28 +00:00
|
|
|
from pydantic import BaseModel as PyBaseModel
|
2020-12-27 16:34:23 +00:00
|
|
|
|
|
|
|
from django.db.models import QuerySet
|
|
|
|
from django.core.exceptions import ObjectDoesNotExist
|
2020-12-27 16:54:06 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2020-12-27 16:34:23 +00:00
|
|
|
|
2020-12-28 10:12:00 +00:00
|
|
|
from django_etebase import app_settings
|
2020-12-27 19:08:00 +00:00
|
|
|
from django_etebase.models import AccessLevels
|
|
|
|
|
2020-12-28 08:00:35 +00:00
|
|
|
from .exceptions import HttpError, HttpErrorOut
|
2020-12-27 16:34:23 +00:00
|
|
|
|
2020-12-27 16:54:06 +00:00
|
|
|
User = get_user_model()
|
|
|
|
|
|
|
|
Prefetch = t.Literal["auto", "medium"]
|
|
|
|
PrefetchQuery = Query(default="auto")
|
|
|
|
|
|
|
|
|
2020-12-28 07:25:28 +00:00
|
|
|
class BaseModel(PyBaseModel):
|
|
|
|
class Config:
|
|
|
|
json_encoders = {
|
|
|
|
bytes: lambda x: x,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-12-27 16:54:06 +00:00
|
|
|
@dataclasses.dataclass
|
|
|
|
class Context:
|
|
|
|
user: t.Optional[User]
|
|
|
|
prefetch: t.Optional[Prefetch]
|
|
|
|
|
2020-12-27 16:34:23 +00:00
|
|
|
|
|
|
|
def get_object_or_404(queryset: QuerySet, **kwargs):
|
|
|
|
try:
|
|
|
|
return queryset.get(**kwargs)
|
|
|
|
except ObjectDoesNotExist as e:
|
2020-12-28 07:51:27 +00:00
|
|
|
raise HttpError("does_not_exist", str(e), status_code=status.HTTP_404_NOT_FOUND)
|
2020-12-27 19:08:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
def is_collection_admin(collection, user):
|
|
|
|
member = collection.members.filter(user=user).first()
|
|
|
|
return (member is not None) and (member.accessLevel == AccessLevels.ADMIN)
|
2020-12-28 08:00:35 +00:00
|
|
|
|
|
|
|
|
2020-12-28 11:56:53 +00:00
|
|
|
def msgpack_encode(content):
|
|
|
|
return msgpack.packb(content, use_bin_type=True)
|
|
|
|
|
|
|
|
|
|
|
|
def msgpack_decode(content):
|
|
|
|
return msgpack.unpackb(content, raw=False)
|
|
|
|
|
|
|
|
|
2020-12-28 12:26:44 +00:00
|
|
|
def b64encode(value):
|
|
|
|
return base64.urlsafe_b64encode(value).decode("ascii").strip("=")
|
|
|
|
|
|
|
|
|
|
|
|
def b64decode(data):
|
|
|
|
data += "=" * ((4 - len(data) % 4) % 4)
|
|
|
|
return base64.urlsafe_b64decode(data)
|
|
|
|
|
|
|
|
|
2020-12-28 10:12:00 +00:00
|
|
|
PERMISSIONS_READ = [Depends(x) for x in app_settings.API_PERMISSIONS_READ]
|
|
|
|
PERMISSIONS_READWRITE = PERMISSIONS_READ + [Depends(x) for x in app_settings.API_PERMISSIONS_WRITE]
|
|
|
|
|
|
|
|
|
2020-12-28 08:00:35 +00:00
|
|
|
response_model_dict = {"model": HttpErrorOut}
|
2020-12-28 08:29:47 +00:00
|
|
|
permission_responses = {401: response_model_dict, 403: response_model_dict}
|