|
| 1 | +from typing import Callable, Optional |
| 2 | + |
| 3 | +from .context import Context |
| 4 | + |
| 5 | +AfterDestroyCallback = Callable[[], None] |
| 6 | + |
| 7 | + |
| 8 | +class Vanity(dict): |
| 9 | + def __init__( |
| 10 | + self, ctx: Context, *, after_destroy: AfterDestroyCallback = lambda: None, **kwargs |
| 11 | + ): |
| 12 | + super().__init__(**kwargs) |
| 13 | + self._ctx = ctx |
| 14 | + self._after_destroy = after_destroy |
| 15 | + |
| 16 | + def destroy(self): |
| 17 | + url = self._ctx.url + f"v1/content/{self['content_guid']}/vanity" |
| 18 | + self._ctx.session.delete(url) |
| 19 | + self._after_destroy() |
| 20 | + |
| 21 | + |
| 22 | +class Vanities: |
| 23 | + def __init__(self, ctx: Context) -> None: |
| 24 | + self._ctx = ctx |
| 25 | + |
| 26 | + def all(self) -> list[Vanity]: |
| 27 | + url = self._ctx.url + f"v1/vanities" |
| 28 | + response = self._ctx.session.get(url) |
| 29 | + results = response.json() |
| 30 | + return [Vanity(self._ctx, **result) for result in results] |
| 31 | + |
| 32 | + |
| 33 | +class VanityContentMixin(dict): |
| 34 | + def __init__(self, ctx: Context, **kwargs): |
| 35 | + super().__init__(**kwargs) |
| 36 | + self._ctx = ctx |
| 37 | + self._vanity: Optional[Vanity] = None |
| 38 | + |
| 39 | + @property |
| 40 | + def vanity(self) -> Vanity: |
| 41 | + if self._vanity is None: |
| 42 | + url = self._ctx.url + f"v1/content/{self['guid']}/vanity" |
| 43 | + response = self._ctx.session.get(url) |
| 44 | + vanity_data = response.json() |
| 45 | + # Set the after_destroy callback to reset _vanity to None when destroyed |
| 46 | + after_destroy = lambda: setattr(self, "_vanity", None) |
| 47 | + self._vanity = Vanity(self._ctx, after_destroy=after_destroy, **vanity_data) |
| 48 | + return self._vanity |
| 49 | + |
| 50 | + @vanity.setter |
| 51 | + def vanity(self, value: dict): |
| 52 | + url = self._ctx.url + f"v1/content/{self['guid']}/vanity" |
| 53 | + self._ctx.session.put(url, json=value) |
| 54 | + # Refresh the vanity property to reflect the updated value |
| 55 | + self._vanity = self.vanity |
| 56 | + |
| 57 | + @vanity.deleter |
| 58 | + def vanity(self): |
| 59 | + if self._vanity: |
| 60 | + self._vanity.destroy() |
0 commit comments