Refactor broadcast message model

There was a lot of duplicate code here for updating the status and other
properties of a broadcast.

This commit abstracts them into reusable methods. They’re named with an
underscore to suggest that they shouldn’t be used externally.
This commit is contained in:
Chris Hill-Scott
2020-07-17 08:07:42 +01:00
parent 73c5aa9bb7
commit 4b1e3ec504

View File

@@ -108,49 +108,39 @@ class BroadcastMessage(JSONModel):
return User.from_id(self.cancelled_by_id) return User.from_id(self.cancelled_by_id)
def add_areas(self, *new_areas): def add_areas(self, *new_areas):
broadcast_message_api_client.update_broadcast_message( self._update(areas=list(OrderedSet(
broadcast_message_id=self.id, self._dict['areas'] + list(new_areas)
service_id=self.service_id, )))
data={
'areas': list(OrderedSet(
self._dict['areas'] + list(new_areas)
))
},
)
def remove_area(self, area_to_remove): def remove_area(self, area_to_remove):
self._update(areas=[
area for area in self._dict['areas']
if area != area_to_remove
])
def _set_status_to(self, status):
broadcast_message_api_client.update_broadcast_message_status(
status,
broadcast_message_id=self.id,
service_id=self.service_id,
)
def _update(self, **kwargs):
broadcast_message_api_client.update_broadcast_message( broadcast_message_api_client.update_broadcast_message(
broadcast_message_id=self.id, broadcast_message_id=self.id,
service_id=self.service_id, service_id=self.service_id,
data={ data=kwargs,
'areas': [
area for area in self._dict['areas']
if area != area_to_remove
]
},
) )
def start_broadcast(self): def start_broadcast(self):
broadcast_message_api_client.update_broadcast_message( self._update(
broadcast_message_id=self.id, starts_at=datetime.utcnow().isoformat(),
service_id=self.service_id, finishes_at=(datetime.utcnow() + self.DEFAULT_TTL).isoformat(),
data={
'starts_at': datetime.utcnow().isoformat(),
'finishes_at': (datetime.utcnow() + self.DEFAULT_TTL).isoformat(),
},
)
broadcast_message_api_client.update_broadcast_message_status(
'broadcasting',
broadcast_message_id=self.id,
service_id=self.service_id,
) )
self._set_status_to('broadcasting')
def cancel_broadcast(self): def cancel_broadcast(self):
broadcast_message_api_client.update_broadcast_message_status( self._set_status_to('cancelled')
'cancelled',
broadcast_message_id=self.id,
service_id=self.service_id,
)
class BroadcastMessages(ModelList): class BroadcastMessages(ModelList):