2020-03-07 01:56:44 -05:00
|
|
|
''' base model with default fields '''
|
2020-02-17 19:50:44 -05:00
|
|
|
from django.db import models
|
2020-05-12 21:56:28 -04:00
|
|
|
from django.dispatch import receiver
|
2020-02-17 19:50:44 -05:00
|
|
|
|
2021-02-04 13:47:03 -05:00
|
|
|
from bookwyrm.settings import DOMAIN
|
|
|
|
from .fields import RemoteIdField
|
2020-02-17 19:50:44 -05:00
|
|
|
|
2020-10-30 14:21:02 -04:00
|
|
|
|
2020-09-21 11:16:34 -04:00
|
|
|
class BookWyrmModel(models.Model):
|
2020-09-17 16:02:52 -04:00
|
|
|
''' shared fields '''
|
2020-02-17 19:50:44 -05:00
|
|
|
created_date = models.DateTimeField(auto_now_add=True)
|
2020-02-20 20:33:50 -05:00
|
|
|
updated_date = models.DateTimeField(auto_now=True)
|
2020-11-30 13:32:13 -05:00
|
|
|
remote_id = RemoteIdField(null=True, activitypub_field='id')
|
2020-02-17 19:50:44 -05:00
|
|
|
|
2020-05-12 21:56:28 -04:00
|
|
|
def get_remote_id(self):
|
|
|
|
''' generate a url that resolves to the local object '''
|
2020-02-17 19:50:44 -05:00
|
|
|
base_path = 'https://%s' % DOMAIN
|
2020-02-20 21:01:50 -05:00
|
|
|
if hasattr(self, 'user'):
|
2021-02-10 14:11:55 -05:00
|
|
|
base_path = '%s%s' % (base_path, self.user.local_path)
|
2020-02-17 20:53:40 -05:00
|
|
|
model_name = type(self).__name__.lower()
|
2020-02-17 19:50:44 -05:00
|
|
|
return '%s/%s/%d' % (base_path, model_name, self.id)
|
|
|
|
|
|
|
|
class Meta:
|
2020-09-17 16:02:52 -04:00
|
|
|
''' this is just here to provide default fields for other models '''
|
2020-02-17 19:50:44 -05:00
|
|
|
abstract = True
|
2020-05-12 21:56:28 -04:00
|
|
|
|
2020-12-30 20:36:35 -05:00
|
|
|
@property
|
|
|
|
def local_path(self):
|
|
|
|
''' how to link to this object in the local app '''
|
|
|
|
return self.get_remote_id().replace('https://%s' % DOMAIN, '')
|
|
|
|
|
2020-05-12 21:56:28 -04:00
|
|
|
|
2020-05-13 21:23:54 -04:00
|
|
|
@receiver(models.signals.post_save)
|
2020-12-12 21:06:48 -05:00
|
|
|
#pylint: disable=unused-argument
|
2020-05-12 21:56:28 -04:00
|
|
|
def execute_after_save(sender, instance, created, *args, **kwargs):
|
|
|
|
''' set the remote_id after save (when the id is available) '''
|
2020-05-13 21:23:54 -04:00
|
|
|
if not created or not hasattr(instance, 'get_remote_id'):
|
2020-05-12 21:56:28 -04:00
|
|
|
return
|
2020-05-14 14:28:45 -04:00
|
|
|
if not instance.remote_id:
|
|
|
|
instance.remote_id = instance.get_remote_id()
|
2021-02-06 19:13:59 -05:00
|
|
|
try:
|
|
|
|
instance.save(broadcast=False)
|
|
|
|
except TypeError:
|
|
|
|
instance.save()
|