blob: 612e925c01f1038181f31646dbfb06b153be2930 [file] [log] [blame]
Siobhan Tully4bc09f22013-04-10 21:15:21 -04001import os
Scott Baker65d5a9a2014-05-26 15:58:09 -07002import sys
Siobhan Tully4bc09f22013-04-10 21:15:21 -04003from django.db import models
Scott Baker13acdd62013-05-08 17:42:56 -07004from django.forms.models import model_to_dict
Scott Bakerc1c45f82014-01-21 16:23:51 -08005from django.core.urlresolvers import reverse
Scott Baker6ecd4262014-01-21 23:15:21 -08006from django.forms.models import model_to_dict
Scott Baker02b59522014-09-17 22:18:46 -07007from django.utils import timezone
Scott Bakere5f41b02014-10-02 22:50:18 -07008from django.core.exceptions import PermissionDenied
Sapan Bhatia39097192014-09-04 00:39:19 -04009import model_policy
Sapan Bhatiaf6613e32014-11-12 10:38:23 -050010from model_autodeletion import ephemeral_models
Scott Baker9e990742014-03-19 22:14:58 -070011
12try:
13 # This is a no-op if observer_disabled is set to 1 in the config file
14 from observer import *
15except:
Scott Baker65d5a9a2014-05-26 15:58:09 -070016 print >> sys.stderr, "import of observer failed! printing traceback and disabling observer:"
Scott Baker9e990742014-03-19 22:14:58 -070017 import traceback
18 traceback.print_exc()
19
20 # guard against something failing
Scott Bakerfd44dfc2014-05-23 13:20:53 -070021 def notify_observer(*args, **kwargs):
Scott Baker9e990742014-03-19 22:14:58 -070022 pass
Siobhan Tully4bc09f22013-04-10 21:15:21 -040023
Sapan Bhatia3089d832014-04-29 14:36:51 -040024# This manager will be inherited by all subclasses because
25# the core model is abstract.
Sapan Bhatia15bf5ac2014-07-21 20:06:59 -040026class PlCoreBaseDeletionManager(models.Manager):
Scott Baker92f14222014-09-12 12:57:27 -070027 def get_queryset(self):
Scott Baker02b59522014-09-17 22:18:46 -070028 parent=super(PlCoreBaseDeletionManager, self)
29 if hasattr(parent, "get_queryset"):
30 return parent.get_queryset().filter(deleted=True)
31 else:
32 return parent.get_query_set().filter(deleted=True)
Sapan Bhatia15bf5ac2014-07-21 20:06:59 -040033
Scott Baker02b59522014-09-17 22:18:46 -070034 # deprecated in django 1.7 in favor of get_queryset().
Scott Baker92f14222014-09-12 12:57:27 -070035 def get_query_set(self):
36 return self.get_queryset()
37
Sapan Bhatia15bf5ac2014-07-21 20:06:59 -040038# This manager will be inherited by all subclasses because
39# the core model is abstract.
Sapan Bhatia4eb663a2014-04-29 14:26:10 -040040class PlCoreBaseManager(models.Manager):
Scott Baker92f14222014-09-12 12:57:27 -070041 def get_queryset(self):
Scott Baker02b59522014-09-17 22:18:46 -070042 parent=super(PlCoreBaseManager, self)
43 if hasattr(parent, "get_queryset"):
44 return parent.get_queryset().filter(deleted=False)
45 else:
46 return parent.get_query_set().filter(deleted=False)
Siobhan Tully4bc09f22013-04-10 21:15:21 -040047
Scott Baker02b59522014-09-17 22:18:46 -070048 # deprecated in django 1.7 in favor of get_queryset().
Scott Baker92f14222014-09-12 12:57:27 -070049 def get_query_set(self):
50 return self.get_queryset()
51
Scott Baker1a6a3902014-10-03 00:32:37 -070052class DiffModelMixIn:
53 # Provides useful methods for computing which objects in a model have
54 # changed. Make sure to do self._initial = self._dict in the __init__
55 # method.
56
57 # This is broken out of PlCoreBase into a Mixin so the User model can
58 # also make use of it.
59
60 @property
61 def _dict(self):
62 return model_to_dict(self, fields=[field.name for field in
63 self._meta.fields])
64
65 @property
66 def diff(self):
67 d1 = self._initial
68 d2 = self._dict
69 diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
70 return dict(diffs)
71
72 @property
73 def has_changed(self):
74 return bool(self.diff)
75
76 @property
77 def changed_fields(self):
78 return self.diff.keys()
79
Scott Baker1a6a3902014-10-03 00:32:37 -070080 def has_field_changed(self, field_name):
81 return field_name in self.diff.keys()
82
83 def get_field_diff(self, field_name):
84 return self.diff.get(field_name, None)
85
Scott Baker82db43c2014-11-06 17:33:27 -080086class PlCoreBase(models.Model): # , DiffModelMixIn):
Sapan Bhatia4eb663a2014-04-29 14:26:10 -040087 objects = PlCoreBaseManager()
Sapan Bhatia15bf5ac2014-07-21 20:06:59 -040088 deleted_objects = PlCoreBaseDeletionManager()
89
Scott Baker82db43c2014-11-06 17:33:27 -080090 # ---- copy stuff from DiffModelMixin ----
91
92 # XXX Django fails miserably when trying to create initial migrations when
93 # DiffModelMixin is used. So, until we figure out what's wrong,
94 # just copied the guts of DiffModelMixIn here.
95
96 @property
97 def _dict(self):
98 return model_to_dict(self, fields=[field.name for field in
99 self._meta.fields])
100
101 @property
102 def diff(self):
103 d1 = self._initial
104 d2 = self._dict
105 diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
106 return dict(diffs)
107
108 @property
109 def has_changed(self):
110 return bool(self.diff)
111
112 @property
113 def changed_fields(self):
114 return self.diff.keys()
115
116 def has_field_changed(self, field_name):
117 return field_name in self.diff.keys()
118
119 def get_field_diff(self, field_name):
120 return self.diff.get(field_name, None)
121 # ---- end copy stuff from DiffModelMixin ----
122
Sapan Bhatia15bf5ac2014-07-21 20:06:59 -0400123 # default values for created and updated are only there to keep evolution
124 # from failing.
Scott Baker02b59522014-09-17 22:18:46 -0700125 created = models.DateTimeField(auto_now_add=True, default=timezone.now)
126 updated = models.DateTimeField(auto_now=True, default=timezone.now)
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400127 enacted = models.DateTimeField(null=True, default=None)
Sapan Bhatia34aee752014-04-28 21:06:39 -0400128 backend_status = models.CharField(max_length=140,
Sapan Bhatiad507f432014-04-29 00:41:39 -0400129 default="Provisioning in progress")
Sapan Bhatiabcc18992014-04-29 10:32:14 -0400130 deleted = models.BooleanField(default=False)
Siobhan Tully4bc09f22013-04-10 21:15:21 -0400131
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400132 class Meta:
Sapan Bhatia3089d832014-04-29 14:36:51 -0400133 # Changing abstract to False would require the managers of subclasses of
134 # PlCoreBase to be customized individually.
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400135 abstract = True
136 app_label = "core"
Siobhan Tully4bc09f22013-04-10 21:15:21 -0400137
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400138 def __init__(self, *args, **kwargs):
139 super(PlCoreBase, self).__init__(*args, **kwargs)
Scott Baker1a6a3902014-10-03 00:32:37 -0700140 self._initial = self._dict # for DiffModelMixIn
Scott Bakerf3f895c2014-09-23 22:41:17 -0700141 self.silent = False
Scott Baker13acdd62013-05-08 17:42:56 -0700142
Tony Mack5b061472014-02-04 07:57:10 -0500143 def can_update(self, user):
144 if user.is_readonly:
145 return False
146 if user.is_admin:
147 return True
Tony Mack5b061472014-02-04 07:57:10 -0500148
Scott Baker1bffe942014-10-06 22:58:48 -0700149 return False
Scott Baker1a6a3902014-10-03 00:32:37 -0700150
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400151 def delete(self, *args, **kwds):
Scott Baker6ecd4262014-01-21 23:15:21 -0800152 # so we have something to give the observer
Sapan Bhatia77d1d892014-07-21 20:07:23 -0400153 purge = kwds.get('purge',False)
Scott Baker3d2d3e42014-10-09 16:22:00 -0700154 if purge:
155 del kwds['purge']
Scott Baker6594bea2014-09-23 16:04:36 -0700156 silent = kwds.get('silent',False)
Scott Baker3d2d3e42014-10-09 16:22:00 -0700157 if silent:
158 del kwds['silent']
Sapan Bhatia77d1d892014-07-21 20:07:23 -0400159 try:
160 purge = purge or observer_disabled
161 except NameError:
162 pass
Scott Baker6594bea2014-09-23 16:04:36 -0700163
Sapan Bhatia77d1d892014-07-21 20:07:23 -0400164 if (purge):
165 super(PlCoreBase, self).delete(*args, **kwds)
Sapan Bhatiac8602432014-04-29 20:33:51 -0400166 else:
167 self.deleted = True
168 self.enacted=None
Scott Baker6594bea2014-09-23 16:04:36 -0700169 self.save(update_fields=['enacted','deleted'], silent=silent)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -0400170
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400171 def save(self, *args, **kwargs):
Scott Bakerf3f895c2014-09-23 22:41:17 -0700172 # let the user specify silence as either a kwarg or an instance varible
173 silent = self.silent
Scott Baker6594bea2014-09-23 16:04:36 -0700174 if "silent" in kwargs:
Scott Bakerf3f895c2014-09-23 22:41:17 -0700175 silent=silent or kwargs.pop("silent")
Scott Baker6594bea2014-09-23 16:04:36 -0700176
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400177 super(PlCoreBase, self).save(*args, **kwargs)
Sapan Bhatiac8602432014-04-29 20:33:51 -0400178
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -0400179 # This is a no-op if observer_disabled is set
Scott Baker6594bea2014-09-23 16:04:36 -0700180 if not silent:
181 notify_observer()
Sapan Bhatia66f4e612013-07-02 12:12:38 -0400182
Scott Baker5e5f4552014-10-03 14:48:06 -0700183 self._initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -0700184
Tony Mack5b061472014-02-04 07:57:10 -0500185 def save_by_user(self, user, *args, **kwds):
Scott Bakere5f41b02014-10-02 22:50:18 -0700186 if not self.can_update(user):
Scott Baker1bffe942014-10-06 22:58:48 -0700187 if getattr(self, "_cant_update_fieldName", None) is not None:
188 raise PermissionDenied("You do not have permission to update field %s on object %s" % (self._cant_update_fieldName, self.__class__.__name__))
189 else:
190 raise PermissionDenied("You do not have permission to update %s objects" % self.__class__.__name__)
Scott Baker1a6a3902014-10-03 00:32:37 -0700191
Scott Bakere5f41b02014-10-02 22:50:18 -0700192 self.save(*args, **kwds)
Tony Mack5b061472014-02-04 07:57:10 -0500193
Tony Mack332ee1d2014-02-04 15:33:45 -0500194 def delete_by_user(self, user, *args, **kwds):
Scott Bakere5f41b02014-10-02 22:50:18 -0700195 if not self.can_update(user):
196 raise PermissionDenied("You do not have permission to delete %s objects" % self.__class__.__name__)
197 self.delete(*args, **kwds)
Tony Mack332ee1d2014-02-04 15:33:45 -0500198
Scott Baker5e5f4552014-10-03 14:48:06 -0700199 @classmethod
200 def select_by_user(cls, user):
201 # This should be overridden by descendant classes that want to perform
202 # filtering of visible objects by user.
203 return cls.objects.all()
204
Sapan Bhatiae33b9dc2014-11-12 10:06:23 -0500205 @classmethod
206 def is_ephemeral(cls):
Sapan Bhatiaf6613e32014-11-12 10:38:23 -0500207 return cls in ephemeral_models
Sapan Bhatiae33b9dc2014-11-12 10:06:23 -0500208
Scott Baker13acdd62013-05-08 17:42:56 -0700209
Siobhan Tully4bc09f22013-04-10 21:15:21 -0400210
211