def subscribe(self, feed: "Feed"): """ Subscribe user to given feed :param feed: feed to subscribe :return: """ if self.feed_subs >= MAX_SUBSCRIPTIONS_FREE: return False # if user is banned from feed he can't subscribe if Ban.by_user_and_feed(self, feed) is not None: return False # save subscription db.table("feeds_users").insert(user_id=self.id, feed_id=feed.id) key = "subs:{}".format(self.id) ids = cache.get(key) or [] ids.append(feed.id) cache.set(key, ids) self.incr("feed_subs", 1) self.update_with_cache() # TODO DO IN QUEUE feed.incr("subscribers_count", 1) return True
def unsubscribe(self, feed: "Feed"): db.table("feeds_users").where("user_id", "=", self.id).where("feed_id", "=", feed.id).delete() self.decr("feed_subs", 1) # TODO DO IN QUEUE feed.decr("subscribers_count", 1) key = "subs:{}".format(self.id) ids = cache.get(key) if ids is not None: ids = [id for id in ids if id != feed.id] cache.set(key, ids) return True
def feeds(self): """ Users subscribed feeds :return: feeds """ return (db.table("feeds").join("feeds_users", "feeds.id", "=", "feeds_users.feed_id").where( "feeds_users.user_id", self.id).get())