def subscribe(self, podcast): """Subscribe the user to the given podcast.""" if podcast.url in self.subscriptions: return SubscribeResult(success=False) self.run(self.table.get(self.id).update({ "subscriptions": r.row["subscriptions"].append(podcast.url) })) Podcast.run(Podcast.get_table().get(podcast.url).update({ "subscribers": (r.row["subscribers"].default(0) + 1) })) return SubscribeResult(success=True)
def unsubscribe(self, podcast): """Unsubscribe the user from the podcast.""" if podcast.url in self.subscriptions: self.run(self.table.get(self.id).update( {"subscriptions": r.row["subscriptions"].set_difference([podcast.url])} )) Podcast.run(Podcast.get_table().get(podcast.url).update({ "subscribers": (r.row["subscribers"].default(0) - 1) })) return True return False
def subscribe_multi(self, podcasts): """Subscribe the user to multiple podcasts. podcasts should be an iterable of Podcast objects.""" not_already_subscribed = [] for podcast in podcasts: if podcast.url not in self.subscriptions: not_already_subscribed.append(podcast.url) self.run(self.table.get(self.id).update( {"subscriptions": r.row["subscriptions"].set_union(not_already_subscribed)} )) Podcast.run(Podcast.get_table().get_all(r.args(not_already_subscribed)).update({ "subscribers": (r.row["subscribers"].default(0) + 1) })) return SubscribeResult(success=True)
def get_subscriptions(self): """Get the Podcast objects of podcasts the user has subscribed to.""" if len(self.subscriptions) == 0: return [] res = self.run(Podcast.get_table().get_all(r.args(self.subscriptions))) return [Podcast.from_dict(p) for p in res]