Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Premium Content Draft #3746

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""add-premium-content-columns

Revision ID: aab240348d73
Revises: 5d3f95470222
Create Date: 2022-08-22 20:22:22.439424

"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "aab240348d73"
down_revision = "5d3f95470222"
branch_labels = None
depends_on = None


def upgrade():
op.add_column(
"tracks",
sa.Column("is_premium", sa.Boolean(), nullable=False, server_default="false"),
)
op.add_column(
"tracks",
sa.Column("premium_conditions", postgresql.JSONB(), nullable=True),
)

connection = op.get_bind()
connection.execute(
"""
begin;
CREATE INDEX IF NOT EXISTS track_is_premium_idx ON tracks (is_premium);
commit;
"""
)


def downgrade():
connection = op.get_bind()
connection.execute(
"""
begin;
DROP INDEX IF EXISTS track_is_premium_idx;
commit;
"""
)

op.drop_column("tracks", "premium_conditions")
op.drop_column("tracks", "is_premium")
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from integration_tests.utils import populate_mock_db
from src.premium_content.premium_content_access_checker import (
PremiumContentAccessChecker,
)
from src.utils.db_session import get_db_read_replica


def test_track_access(app):
with app.app_context():
db = get_db_read_replica()

user_entities = [{"user_id": 1}, {"user_id": 2}]
non_premium_track_entity = {
"track_id": 1,
"is_premium": False,
"premium_conditions": None,
}
premium_track_entity = {
"track_id": 2,
"is_premium": True,
"premium_conditions": {"nft-collection": "some-nft-collection"},
}
track_entities = [non_premium_track_entity, premium_track_entity]
entities = {"users": user_entities, "tracks": track_entities}

populate_mock_db(db, entities)

premium_content_access_checker = PremiumContentAccessChecker()

# test non-existent track
non_exisent_track_id = 3
is_premium, does_user_have_access = premium_content_access_checker.check_access(
user_entities[0]["user_id"], non_exisent_track_id, "track"
)
assert not is_premium and does_user_have_access

# test non-premium track
is_premium, does_user_have_access = premium_content_access_checker.check_access(
user_entities[1]["user_id"], non_premium_track_entity["track_id"], "track"
)
assert not is_premium and does_user_have_access

# test premium track with user who has access
is_premium, does_user_have_access = premium_content_access_checker.check_access(
user_entities[1]["user_id"], premium_track_entity["track_id"], "track"
)
assert is_premium and does_user_have_access

# todo: test premium track with user who has no access
# after we implement nft infexing
2 changes: 2 additions & 0 deletions discovery-provider/integration_tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ def populate_mock_db(db, entities, block_offset=None):
created_at=track_meta.get("created_at", datetime.now()),
release_date=track_meta.get("release_date", None),
is_unlisted=track_meta.get("is_unlisted", False),
is_premium=track_meta.get("is_premium", False),
premium_conditions=track_meta.get("premium_conditions", None),
)
session.add(track)
for i, playlist_meta in enumerate(playlists):
Expand Down
2 changes: 2 additions & 0 deletions discovery-provider/src/models/tracks/track.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ class Track(Base, RepresentableMixin):
)
slot = Column(Integer)
is_available = Column(Boolean, nullable=False, server_default=text("true"))
is_premium = Column(Boolean, nullable=False, server_default=text("false"))
premium_conditions = Column(JSONB())

block = relationship( # type: ignore
"Block", primaryjoin="Track.blockhash == Block.blockhash"
Expand Down
13 changes: 13 additions & 0 deletions discovery-provider/src/premium_content/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import logging

# from src.utils import db_session

logger = logging.getLogger(__name__)


def does_user_have_nft_collection(user_id: int, nft_collection: str):
# todo: check whether user has the nft from some user_wallet_nfts table
# which is populated during nft indexing
# db = db_session.get_db_read_replica()
# with db.scoped_session() as session:
return True
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import json
import logging
from typing import Dict, Optional, Tuple

from src.models.tracks.track import Track
from src.premium_content.helpers import does_user_have_nft_collection
from src.premium_content.types import PremiumContentType
from src.utils import db_session

logger = logging.getLogger(__name__)


class PremiumContentAccessChecker:
# check if content is premium
# - if not, then user has access
# - if so, check whether user fulfills the conditions
#
# Returns a tuple of (bool, bool) -> (track is premium, user has access)
#
# Note: premium content id for type should exist, but just in case it does not,
# we return true for user access so that (non-existent) track does not change
# existing flow of the function caller.
def check_access(
self,
user_id: int,
premium_content_id: int,
premium_content_type: PremiumContentType,
) -> Tuple[bool, bool]:
# for now, we only allow tracks to be premium
# premium playlists will come later
if premium_content_type != "track":
return False, True

(
is_premium,
premium_conditions,
content_owner_id,
) = self._is_content_premium(premium_content_id)

if not is_premium:
# premium_conditions should always be null here as it makes
# no sense to have a non-premium track with conditions
if premium_conditions:
logger.warn(
f"premium_content_access_checker.py | _aggregate_conditions | non-premium content with id {premium_content_id} and type {premium_content_type} has premium conditions."
)
return False, True

if not premium_conditions:
# is_premium should always be false here as it makes
# no sense to have a premium track with no conditions
if is_premium:
logger.warn(
f"premium_content_access_checker.py | _aggregate_conditions | premium content with id {premium_content_id} and type {premium_content_type} has no premium conditions."
)
return is_premium, True

does_user_have_access = self._evaluate_conditions(
user_id, content_owner_id, premium_conditions
)
return True, does_user_have_access

# Returns a tuple of (bool, Dict | None, int | None) -> (track is premium, track premium conditions, track owner id)
def _is_content_premium(
self, premium_content_id: int
) -> Tuple[bool, Optional[Dict], Optional[int]]:
db = db_session.get_db_read_replica()
with db.scoped_session() as session:
track = (
session.query(Track)
.filter(
Track.track_id == premium_content_id,
Track.is_current == True,
Track.is_delete == False,
)
.first()
)

if not track:
return False, None, None

return track.is_premium, track.premium_conditions, track.owner_id

# There will eventually be another step prior to this one where
# we aggregate multiple conditions and evaluate them altogether.
# For now, we only support one condition, which is the ownership
# of an NFT from a given collection.
def _evaluate_conditions(
self, user_id: int, track_owner_id: int, premium_conditions: Dict
):
if len(premium_conditions) != 1:
logging.info(
f"premium_content_access_checker.py | _aggregate_conditions | invalid conditions: {json.dumps(premium_conditions)}"
)
return False

condition, value = list(premium_conditions.items())[0]
if condition != "nft-collection":
return False

return does_user_have_nft_collection(user_id, value)


premium_content_access_checker = PremiumContentAccessChecker()
5 changes: 2 additions & 3 deletions discovery-provider/src/premium_content/signature.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from datetime import datetime
from typing import Literal, TypedDict, cast
from typing import TypedDict, cast

from src.api_helpers import generate_signature

PremiumContentType = Literal["track"]
from src.premium_content.types import PremiumContentType


class PremiumContentSignatureData(TypedDict):
Expand Down
16 changes: 16 additions & 0 deletions discovery-provider/src/premium_content/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from enum import Enum
from typing import Literal

# These are the different types of content that can be made premium.
# For now, we only support tracks.
PremiumContentType = Literal["track"]

# These are the different conditions on which premium content access
# will be gated.
# They should match the PremiumConditions property in the track schema
# in src/schemas/track_schema.json
PremiumContentConditions = Literal["nft-collection"]

# This is for when we support the combination of different conditions
# for premium content access based on AND'ing / OR'ing them together.
PremiumContentConditionGates = Literal["AND", "OR"]
Loading