diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..b8ca00e43126706bcc2984fec9d333f282205587 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.venv/ +__pycache__/ +*.pyc +.git/ +.github/ +.env +logs/ +static/uploads/ +.pytest_cache/ +tests/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..51a6c5cd46c0b6b320098cd7d203eb75490e607f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,32 @@ +FROM python:3.13-slim + +# Prevent Python from writing pyc files and buffering stdout/stderr +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + PORT=7860 + +WORKDIR /app + +# Install system dependencies (build-essential, libpq-dev for Postgres, curl) +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + libpq-dev \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Copy only requirements first to leverage Docker layer caching +COPY requirements.txt . +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements.txt + +# Copy the rest of the application code +COPY . . + +# Make startup script executable +RUN chmod +x start.sh + +# Hugging Face Spaces requires port 7860 +EXPOSE 7860 + +# Start Celery worker in background, then launch uvicorn on port 7860 +CMD ["./start.sh"] diff --git a/README.md b/README.md index 353db7a1fbcf4448b75d81e45b06314399a4407a..7b53a6f5ffe677e78bf9440001259af044f0dc64 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ --- -title: Backend -emoji: 🌍 -colorFrom: green -colorTo: indigo +title: Monteeq Backend +emoji: 🎬 +colorFrom: indigo +colorTo: purple sdk: docker +app_port: 7860 pinned: false -license: apache-2.0 -short_description: fastapi of monteeq --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# Monteeq Backend API + +FastAPI backend for the Monteeq video platform. + +- **API Docs**: [/docs](https://monteeqorg-backend.hf.space/docs) +- **Health Check**: [/health](https://monteeqorg-backend.hf.space/health) diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000000000000000000000000000000000000..aa5eeed9ad3f54830913aba561436423535655e5 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,149 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +# sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/alembic/README b/alembic/README new file mode 100644 index 0000000000000000000000000000000000000000..98e4f9c44effe479ed38c66ba922e7bcc672916f --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000000000000000000000000000000000000..dd97378e5821ff6d1e3da3a7fdb1598ff30cd409 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,91 @@ +import sys +import os +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# Add current directory to path to import app +sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))) + +from app.models.models import Base +from app.core.config import DATABASE_URL + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Set sqlalchemy.url from environment +config.set_main_option("sqlalchemy.url", DATABASE_URL) + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + configuration = config.get_section(config.config_ini_section, {}) + configuration["sqlalchemy.url"] = DATABASE_URL + connectable = engine_from_config( + configuration, + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000000000000000000000000000000000000..11016301e749297acb67822efc7974ee53c905c6 --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/alembic/versions/0696864b4ef4_add_2fa_and_sessions.py b/alembic/versions/0696864b4ef4_add_2fa_and_sessions.py new file mode 100644 index 0000000000000000000000000000000000000000..0b0a7b86afcab8cfe231a9d2e73e03f6753c0287 --- /dev/null +++ b/alembic/versions/0696864b4ef4_add_2fa_and_sessions.py @@ -0,0 +1,58 @@ +"""add_2fa_and_sessions + +Revision ID: 0696864b4ef4 +Revises: 0ae5df15b305 +Create Date: 2026-04-06 20:02:31.210128 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '0696864b4ef4' +down_revision: Union[str, Sequence[str], None] = '0ae5df15b305' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('user_sessions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('token_hash', sa.String(), nullable=True), + sa.Column('device_info', sa.String(), nullable=True), + sa.Column('ip_address', sa.String(), nullable=True), + sa.Column('last_active', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('user_sessions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_user_sessions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_user_sessions_token_hash'), ['token_hash'], unique=False) + + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.add_column(sa.Column('totp_secret', sa.String(), nullable=True)) + batch_op.add_column(sa.Column('is_active', sa.Boolean(), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_column('is_active') + batch_op.drop_column('totp_secret') + + with op.batch_alter_table('user_sessions', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_user_sessions_token_hash')) + batch_op.drop_index(batch_op.f('ix_user_sessions_id')) + + op.drop_table('user_sessions') + # ### end Alembic commands ### diff --git a/alembic/versions/0ae5df15b305_sync_user_settings_and_cleanup.py b/alembic/versions/0ae5df15b305_sync_user_settings_and_cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1f8b5e1bf17333abac161da69b2a42ccea7e16 --- /dev/null +++ b/alembic/versions/0ae5df15b305_sync_user_settings_and_cleanup.py @@ -0,0 +1,212 @@ +""""sync_user_settings_and_cleanup" + +Revision ID: 0ae5df15b305 +Revises: c6b4627fe974 +Create Date: 2026-04-06 19:32:40.650876 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '0ae5df15b305' +down_revision: Union[str, Sequence[str], None] = 'c6b4627fe974' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.execute('DROP TABLE IF EXISTS "Post" CASCADE') + op.execute('DROP TABLE IF EXISTS "View" CASCADE') + op.execute('DROP TABLE IF EXISTS "Comment" CASCADE') + op.execute('DROP TABLE IF EXISTS "Repost" CASCADE') + op.execute('DROP TABLE IF EXISTS "Video" CASCADE') + op.execute('DROP TABLE IF EXISTS "VerificationCode" CASCADE') + op.execute('DROP TABLE IF EXISTS "User" CASCADE') + op.execute('DROP TABLE IF EXISTS "Like" CASCADE') + op.execute('DROP TABLE IF EXISTS "Follow" CASCADE') + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.add_column(sa.Column('show_wins', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('show_trophies', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('notif_new_follower', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('notif_challenge_win', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('notif_comments', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('notif_likes', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('email_weekly', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('email_challenges', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('email_payouts', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('email_marketing', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('payout_method', sa.String(), nullable=True)) + batch_op.add_column(sa.Column('two_factor_enabled', sa.Boolean(), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_column('two_factor_enabled') + batch_op.drop_column('payout_method') + batch_op.drop_column('email_marketing') + batch_op.drop_column('email_payouts') + batch_op.drop_column('email_challenges') + batch_op.drop_column('email_weekly') + batch_op.drop_column('notif_likes') + batch_op.drop_column('notif_comments') + batch_op.drop_column('notif_challenge_win') + batch_op.drop_column('notif_new_follower') + batch_op.drop_column('show_trophies') + batch_op.drop_column('show_wins') + + op.create_table('Follow', + sa.Column('follower_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('followed_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.CheckConstraint('follower_id <> followed_id', name=op.f('Follow_check')), + sa.ForeignKeyConstraint(['followed_id'], ['User.id'], name=op.f('Follow_followed_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['follower_id'], ['User.id'], name=op.f('Follow_follower_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('follower_id', 'followed_id', name=op.f('Follow_pkey')) + ) + with op.batch_alter_table('Follow', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_follow_follower'), ['follower_id'], unique=False) + batch_op.create_index(batch_op.f('idx_follow_followed'), ['followed_id'], unique=False) + + op.create_table('Like', + sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['User.id'], name=op.f('Like_user_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('Like_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('user_id', 'video_id', name=op.f('Like_pkey')) + ) + with op.batch_alter_table('Like', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_like_video'), ['video_id'], unique=False) + + op.create_table('User', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('username', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('full_name', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('email', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('hashed_password', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('google_id', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('role', sa.VARCHAR(), server_default=sa.text("'user'::character varying"), autoincrement=False, nullable=False), + sa.Column('is_premium', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True), + sa.Column('is_verified', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True), + sa.Column('is_onboarded', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True), + sa.Column('profile_pic', sa.VARCHAR(), server_default=sa.text("'http://localhost:8000/static/defaults/default_avatar.png'::character varying"), autoincrement=False, nullable=True), + sa.Column('flash_uploads', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('home_uploads', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('bio', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('id', name=op.f('User_pkey')), + sa.UniqueConstraint('email', name=op.f('User_email_key'), postgresql_include=[], postgresql_nulls_not_distinct=False), + sa.UniqueConstraint('google_id', name=op.f('User_google_id_key'), postgresql_include=[], postgresql_nulls_not_distinct=False), + sa.UniqueConstraint('username', name=op.f('User_username_key'), postgresql_include=[], postgresql_nulls_not_distinct=False) + ) + with op.batch_alter_table('User', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_user_username'), ['username'], unique=False) + batch_op.create_index(batch_op.f('idx_user_google_id'), ['google_id'], unique=False) + batch_op.create_index(batch_op.f('idx_user_email'), ['email'], unique=False) + + op.create_table('VerificationCode', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('email', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('code', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('expires_at', postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('id', name=op.f('VerificationCode_pkey')) + ) + with op.batch_alter_table('VerificationCode', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_verification_email'), ['email'], unique=False) + + op.create_table('Video', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('video_url', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('url_480p', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_720p', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_1080p', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_2k', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_4k', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('thumbnail_url', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('video_type', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('status', sa.VARCHAR(), server_default=sa.text("'pending'::character varying"), autoincrement=False, nullable=True), + sa.Column('owner_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('views', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('earnings', sa.NUMERIC(precision=10, scale=2), server_default=sa.text('0.0'), autoincrement=False, nullable=True), + sa.Column('shares', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('duration', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('processing_key', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['User.id'], name=op.f('Video_owner_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Video_pkey')) + ) + with op.batch_alter_table('Video', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_video_type'), ['video_type'], unique=False) + batch_op.create_index(batch_op.f('idx_video_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('idx_video_owner'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('idx_video_created'), [sa.literal_column('created_at DESC')], unique=False) + + op.create_table('Repost', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['User.id'], name=op.f('Repost_user_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('Repost_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Repost_pkey')) + ) + with op.batch_alter_table('Repost', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_repost_video'), ['video_id'], unique=False) + batch_op.create_index(batch_op.f('idx_repost_user'), ['user_id'], unique=False) + + op.create_table('Comment', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('content', sa.TEXT(), autoincrement=False, nullable=False), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('owner_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['User.id'], name=op.f('Comment_owner_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('Comment_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Comment_pkey')) + ) + with op.batch_alter_table('Comment', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_comment_video'), ['video_id'], unique=False) + batch_op.create_index(batch_op.f('idx_comment_owner'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('idx_comment_created'), [sa.literal_column('created_at DESC')], unique=False) + + op.create_table('View', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['User.id'], name=op.f('View_user_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('View_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('View_pkey')) + ) + with op.batch_alter_table('View', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_view_video'), ['video_id'], unique=False) + batch_op.create_index(batch_op.f('idx_view_user'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('idx_view_created'), ['created_at'], unique=False) + + op.create_table('Post', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('content', sa.TEXT(), autoincrement=False, nullable=False), + sa.Column('image_url', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('owner_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('is_active', sa.BOOLEAN(), server_default=sa.text('true'), autoincrement=False, nullable=True), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['User.id'], name=op.f('Post_owner_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Post_pkey')) + ) + with op.batch_alter_table('Post', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_post_owner'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('idx_post_created'), [sa.literal_column('created_at DESC')], unique=False) + + # ### end Alembic commands ### diff --git a/alembic/versions/0d4c4236b249_add_prekeys.py b/alembic/versions/0d4c4236b249_add_prekeys.py new file mode 100644 index 0000000000000000000000000000000000000000..c13ec113a8675d4f594a0a9d4ab03a9bb8d15db3 --- /dev/null +++ b/alembic/versions/0d4c4236b249_add_prekeys.py @@ -0,0 +1,70 @@ +"""add_prekeys + +Revision ID: 0d4c4236b249 +Revises: 408279214832 +Create Date: 2026-05-30 00:26:56.197123 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '0d4c4236b249' +down_revision: Union[str, Sequence[str], None] = '408279214832' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('user_device_prekey_bundles', + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('device_id', sa.String(), nullable=False), + sa.Column('identity_key', sa.Text(), nullable=False), + sa.Column('signed_prekey', sa.Text(), nullable=False), + sa.Column('signed_prekey_signature', sa.Text(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('user_id', 'device_id') + ) + with op.batch_alter_table('user_device_prekey_bundles', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_user_device_prekey_bundles_device_id'), ['device_id'], unique=False) + batch_op.create_index(batch_op.f('ix_user_device_prekey_bundles_user_id'), ['user_id'], unique=False) + + op.create_table('user_one_time_prekeys', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('device_id', sa.String(), nullable=True), + sa.Column('key_value', sa.Text(), nullable=False), + sa.Column('used', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('user_one_time_prekeys', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_user_one_time_prekeys_device_id'), ['device_id'], unique=False) + batch_op.create_index(batch_op.f('ix_user_one_time_prekeys_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_user_one_time_prekeys_user_id'), ['user_id'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('user_one_time_prekeys', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_user_one_time_prekeys_user_id')) + batch_op.drop_index(batch_op.f('ix_user_one_time_prekeys_id')) + batch_op.drop_index(batch_op.f('ix_user_one_time_prekeys_device_id')) + + op.drop_table('user_one_time_prekeys') + with op.batch_alter_table('user_device_prekey_bundles', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_user_device_prekey_bundles_user_id')) + batch_op.drop_index(batch_op.f('ix_user_device_prekey_bundles_device_id')) + + op.drop_table('user_device_prekey_bundles') + # ### end Alembic commands ### diff --git a/alembic/versions/1cb317046980_add_comment_likes_columns.py b/alembic/versions/1cb317046980_add_comment_likes_columns.py new file mode 100644 index 0000000000000000000000000000000000000000..abfeb74800a50848442d48cfd73d150c7574cb9e --- /dev/null +++ b/alembic/versions/1cb317046980_add_comment_likes_columns.py @@ -0,0 +1,46 @@ +"""add_comment_likes_columns + +Revision ID: 1cb317046980 +Revises: 62c65d9d9b3b +Create Date: 2026-06-08 00:23:25.580042 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '1cb317046980' +down_revision: Union[str, Sequence[str], None] = '62c65d9d9b3b' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('comments', schema=None) as batch_op: + batch_op.add_column(sa.Column('likes_count', sa.Integer(), nullable=True)) + + with op.batch_alter_table('likes', schema=None) as batch_op: + batch_op.add_column(sa.Column('comment_id', sa.Integer(), nullable=True)) + batch_op.create_index(batch_op.f('ix_likes_comment_id'), ['comment_id'], unique=False) + batch_op.create_foreign_key(None, 'comments', ['comment_id'], ['id'], ondelete='CASCADE') + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('likes', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_likes_comment_id')) + batch_op.drop_column('comment_id') + + with op.batch_alter_table('comments', schema=None) as batch_op: + batch_op.drop_column('likes_count') + + # ### end Alembic commands ### diff --git a/alembic/versions/219cc7d232b2_add_watch_history_column_to_user_.py b/alembic/versions/219cc7d232b2_add_watch_history_column_to_user_.py new file mode 100644 index 0000000000000000000000000000000000000000..c0955b08854dc6c0bc6cadf3b35e925d1296a72f --- /dev/null +++ b/alembic/versions/219cc7d232b2_add_watch_history_column_to_user_.py @@ -0,0 +1,36 @@ +"""add watch_history column to user_recommendation_profiles + +Revision ID: 219cc7d232b2 +Revises: b1506accc1d5 +Create Date: 2026-04-16 03:04:22.759263 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '219cc7d232b2' +down_revision: Union[str, Sequence[str], None] = 'b1506accc1d5' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('user_recommendation_profiles', schema=None) as batch_op: + batch_op.add_column(sa.Column('watch_history', sa.Text(), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('user_recommendation_profiles', schema=None) as batch_op: + batch_op.drop_column('watch_history') + + # ### end Alembic commands ### diff --git a/alembic/versions/2e5874e941aa_add_monetization_tables.py b/alembic/versions/2e5874e941aa_add_monetization_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..f201d5d5550bd9475a4079b2e30cfd16785aeae1 --- /dev/null +++ b/alembic/versions/2e5874e941aa_add_monetization_tables.py @@ -0,0 +1,112 @@ +"""Add monetization tables + +Revision ID: 2e5874e941aa +Revises: de8fb49fe9ad +Create Date: 2026-04-07 00:20:05.367355 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '2e5874e941aa' +down_revision: Union[str, Sequence[str], None] = 'de8fb49fe9ad' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('subscriptions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('subscriber_id', sa.Integer(), nullable=True), + sa.Column('creator_id', sa.Integer(), nullable=True), + sa.Column('monthly_price', sa.Numeric(precision=12, scale=2), nullable=True), + sa.Column('status', sa.String(), nullable=True), + sa.Column('next_billing_date', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['creator_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['subscriber_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('subscriptions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_subscriptions_creator_id'), ['creator_id'], unique=False) + batch_op.create_index(batch_op.f('ix_subscriptions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_subscriptions_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('ix_subscriptions_subscriber_id'), ['subscriber_id'], unique=False) + + op.create_table('wallets', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('balance', sa.Numeric(precision=12, scale=2), nullable=True), + sa.Column('currency', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('wallets', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_wallets_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_wallets_user_id'), ['user_id'], unique=True) + + op.create_table('transactions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('wallet_id', sa.Integer(), nullable=True), + sa.Column('amount', sa.Numeric(precision=12, scale=2), nullable=True), + sa.Column('transaction_type', sa.String(), nullable=True), + sa.Column('reference_id', sa.String(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['wallet_id'], ['wallets.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('transactions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_transactions_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_reference_id'), ['reference_id'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_transaction_type'), ['transaction_type'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_wallet_id'), ['wallet_id'], unique=False) + + with op.batch_alter_table('posts', schema=None) as batch_op: + batch_op.add_column(sa.Column('is_exclusive', sa.Boolean(), nullable=True)) + + with op.batch_alter_table('videos', schema=None) as batch_op: + batch_op.add_column(sa.Column('is_exclusive', sa.Boolean(), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('videos', schema=None) as batch_op: + batch_op.drop_column('is_exclusive') + + with op.batch_alter_table('posts', schema=None) as batch_op: + batch_op.drop_column('is_exclusive') + + with op.batch_alter_table('transactions', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_transactions_wallet_id')) + batch_op.drop_index(batch_op.f('ix_transactions_transaction_type')) + batch_op.drop_index(batch_op.f('ix_transactions_reference_id')) + batch_op.drop_index(batch_op.f('ix_transactions_id')) + batch_op.drop_index(batch_op.f('ix_transactions_created_at')) + + op.drop_table('transactions') + with op.batch_alter_table('wallets', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_wallets_user_id')) + batch_op.drop_index(batch_op.f('ix_wallets_id')) + + op.drop_table('wallets') + with op.batch_alter_table('subscriptions', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_subscriptions_subscriber_id')) + batch_op.drop_index(batch_op.f('ix_subscriptions_status')) + batch_op.drop_index(batch_op.f('ix_subscriptions_id')) + batch_op.drop_index(batch_op.f('ix_subscriptions_creator_id')) + + op.drop_table('subscriptions') + # ### end Alembic commands ### diff --git a/alembic/versions/3a5babf76aab_add_multi_modal_support_to_chatmessage.py b/alembic/versions/3a5babf76aab_add_multi_modal_support_to_chatmessage.py new file mode 100644 index 0000000000000000000000000000000000000000..260e40c0b31f3cb97a998fce503fe8c853d1aed4 --- /dev/null +++ b/alembic/versions/3a5babf76aab_add_multi_modal_support_to_chatmessage.py @@ -0,0 +1,35 @@ +"""Add multi-modal support to ChatMessage + +Revision ID: 3a5babf76aab +Revises: f3b1a2c4e5d6 +Create Date: 2026-04-12 18:14:47.013924 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '3a5babf76aab' +down_revision: Union[str, Sequence[str], None] = 'f3b1a2c4e5d6' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # Add multi-modal columns to ChatMessage + with op.batch_alter_table('chat_messages', schema=None) as batch_op: + batch_op.add_column(sa.Column('message_type', sa.String(), nullable=True)) + batch_op.add_column(sa.Column('attachment_url', sa.String(), nullable=True)) + batch_op.add_column(sa.Column('file_metadata', sa.Text(), nullable=True)) + + +def downgrade() -> None: + """Downgrade schema.""" + with op.batch_alter_table('chat_messages', schema=None) as batch_op: + batch_op.drop_column('file_metadata') + batch_op.drop_column('attachment_url') + batch_op.drop_column('message_type') diff --git a/alembic/versions/408279214832_add_premium_expires_at_to_user.py b/alembic/versions/408279214832_add_premium_expires_at_to_user.py new file mode 100644 index 0000000000000000000000000000000000000000..43f9fa98b1b111e68c5f70086c05fffcd7fae7c4 --- /dev/null +++ b/alembic/versions/408279214832_add_premium_expires_at_to_user.py @@ -0,0 +1,36 @@ +"""add premium_expires_at to user + +Revision ID: 408279214832 +Revises: 806aa527dfad +Create Date: 2026-05-15 23:20:33.855001 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '408279214832' +down_revision: Union[str, Sequence[str], None] = '806aa527dfad' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.add_column(sa.Column('premium_expires_at', sa.DateTime(timezone=True), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_column('premium_expires_at') + + # ### end Alembic commands ### diff --git a/alembic/versions/4c7e702c81d7_add_recovery_codes.py b/alembic/versions/4c7e702c81d7_add_recovery_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..fb9e54cc3dda741a13fcfe653ad7d57c005478d6 --- /dev/null +++ b/alembic/versions/4c7e702c81d7_add_recovery_codes.py @@ -0,0 +1,36 @@ +"""add_recovery_codes + +Revision ID: 4c7e702c81d7 +Revises: 0696864b4ef4 +Create Date: 2026-04-06 20:32:04.450868 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '4c7e702c81d7' +down_revision: Union[str, Sequence[str], None] = '0696864b4ef4' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.add_column(sa.Column('recovery_codes', sa.Text(), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_column('recovery_codes') + + # ### end Alembic commands ### diff --git a/alembic/versions/553a88ea49e2_add_public_id_to_video.py b/alembic/versions/553a88ea49e2_add_public_id_to_video.py new file mode 100644 index 0000000000000000000000000000000000000000..4d30dd76992b40629bc98cff09691c9e861c9bdc --- /dev/null +++ b/alembic/versions/553a88ea49e2_add_public_id_to_video.py @@ -0,0 +1,32 @@ +"""add_public_id_to_video + +Revision ID: 553a88ea49e2 +Revises: 0d4c4236b249 +Create Date: 2026-06-01 22:02:03.583845 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '553a88ea49e2' +down_revision: Union[str, Sequence[str], None] = '0d4c4236b249' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + op.add_column('videos', sa.Column('public_id', sa.String(), nullable=True)) + op.execute("UPDATE videos SET public_id = 'vid_' || substring(md5(random()::text), 1, 16) WHERE public_id IS NULL") + op.create_index(op.f('ix_videos_public_id'), 'videos', ['public_id'], unique=True) + + +def downgrade() -> None: + """Downgrade schema.""" + op.drop_index(op.f('ix_videos_public_id'), table_name='videos') + op.drop_column('videos', 'public_id') + diff --git a/alembic/versions/55ef522b3e8c_add_missing_columns.py b/alembic/versions/55ef522b3e8c_add_missing_columns.py new file mode 100644 index 0000000000000000000000000000000000000000..a00ebe47a4d3a9ad0e06202df5f81caa1afd04fc --- /dev/null +++ b/alembic/versions/55ef522b3e8c_add_missing_columns.py @@ -0,0 +1,32 @@ +"""Add missing columns + +Revision ID: 55ef522b3e8c +Revises: abdefa368e36 +Create Date: 2026-04-28 11:44:29.346216 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '55ef522b3e8c' +down_revision: Union[str, Sequence[str], None] = 'abdefa368e36' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### diff --git a/alembic/versions/62c65d9d9b3b_add_content_reporting_and_audit_logs.py b/alembic/versions/62c65d9d9b3b_add_content_reporting_and_audit_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..6a5207ccc964d0027c7c3f65fc35dcb1f38d3a87 --- /dev/null +++ b/alembic/versions/62c65d9d9b3b_add_content_reporting_and_audit_logs.py @@ -0,0 +1,115 @@ +"""add content reporting and audit logs + +Revision ID: 62c65d9d9b3b +Revises: 553a88ea49e2 +Create Date: 2026-06-07 22:40:27.738090 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '62c65d9d9b3b' +down_revision: Union[str, Sequence[str], None] = '553a88ea49e2' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('email_log', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('template', sa.String(length=100), nullable=False), + sa.Column('subject', sa.String(length=300), nullable=True), + sa.Column('sent_at', sa.DateTime(), nullable=False), + sa.Column('opened_at', sa.DateTime(), nullable=True), + sa.Column('clicked_at', sa.DateTime(), nullable=True), + sa.Column('bounced', sa.Boolean(), nullable=True), + sa.Column('unsubscribed', sa.Boolean(), nullable=True), + sa.Column('esp_message_id', sa.String(length=200), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('email_log', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_email_log_bounced'), ['bounced'], unique=False) + batch_op.create_index(batch_op.f('ix_email_log_esp_message_id'), ['esp_message_id'], unique=False) + batch_op.create_index(batch_op.f('ix_email_log_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_email_log_sent_at'), ['sent_at'], unique=False) + batch_op.create_index(batch_op.f('ix_email_log_template'), ['template'], unique=False) + batch_op.create_index(batch_op.f('ix_email_log_user_id'), ['user_id'], unique=False) + batch_op.create_index('ix_email_log_user_template_sent', ['user_id', 'template', 'sent_at'], unique=False) + + op.create_table('moderation_audit_logs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('action', sa.String(), nullable=False), + sa.Column('moderator_id', sa.Integer(), nullable=True), + sa.Column('target_type', sa.String(), nullable=False), + sa.Column('target_id', sa.String(), nullable=False), + sa.Column('details', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['moderator_id'], ['users.id'], ondelete='SET NULL'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('moderation_audit_logs', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_moderation_audit_logs_id'), ['id'], unique=False) + + op.create_table('content_reports', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('reporter_id', sa.Integer(), nullable=False), + sa.Column('content_type', sa.String(), nullable=False), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('post_id', sa.Integer(), nullable=True), + sa.Column('comment_id', sa.Integer(), nullable=True), + sa.Column('reason', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.String(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('resolved_at', sa.DateTime(), nullable=True), + sa.Column('resolved_by', sa.Integer(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['comment_id'], ['comments.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['reporter_id'], ['users.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['resolved_by'], ['users.id'], ondelete='SET NULL'), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('content_reports', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_content_reports_id'), ['id'], unique=False) + + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_users_stripe_customer_id'), ['stripe_customer_id'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_users_stripe_customer_id')) + + with op.batch_alter_table('content_reports', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_content_reports_id')) + + op.drop_table('content_reports') + with op.batch_alter_table('moderation_audit_logs', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_moderation_audit_logs_id')) + + op.drop_table('moderation_audit_logs') + with op.batch_alter_table('email_log', schema=None) as batch_op: + batch_op.drop_index('ix_email_log_user_template_sent') + batch_op.drop_index(batch_op.f('ix_email_log_user_id')) + batch_op.drop_index(batch_op.f('ix_email_log_template')) + batch_op.drop_index(batch_op.f('ix_email_log_sent_at')) + batch_op.drop_index(batch_op.f('ix_email_log_id')) + batch_op.drop_index(batch_op.f('ix_email_log_esp_message_id')) + batch_op.drop_index(batch_op.f('ix_email_log_bounced')) + + op.drop_table('email_log') + # ### end Alembic commands ### diff --git a/alembic/versions/6beb84aaed26_add_settings_table.py b/alembic/versions/6beb84aaed26_add_settings_table.py new file mode 100644 index 0000000000000000000000000000000000000000..055a79310b9ff667f2c3a3513bad4727216dc8f7 --- /dev/null +++ b/alembic/versions/6beb84aaed26_add_settings_table.py @@ -0,0 +1,186 @@ +"""add settings table + +Revision ID: 6beb84aaed26 +Revises: 7c01ead0ba2b +Create Date: 2026-04-01 21:23:35.843936 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '6beb84aaed26' +down_revision: Union[str, Sequence[str], None] = '7c01ead0ba2b' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('settings', + sa.Column('key', sa.String(), nullable=False), + sa.Column('value', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('key') + ) + with op.batch_alter_table('settings', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_settings_key'), ['key'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('View', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['User.id'], name=op.f('View_user_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('View_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('View_pkey')) + ) + with op.batch_alter_table('View', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_view_video'), ['video_id'], unique=False) + batch_op.create_index(batch_op.f('idx_view_user'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('idx_view_created'), ['created_at'], unique=False) + + op.create_table('Follow', + sa.Column('follower_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('followed_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.CheckConstraint('follower_id <> followed_id', name=op.f('Follow_check')), + sa.ForeignKeyConstraint(['followed_id'], ['User.id'], name=op.f('Follow_followed_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['follower_id'], ['User.id'], name=op.f('Follow_follower_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('follower_id', 'followed_id', name=op.f('Follow_pkey')) + ) + with op.batch_alter_table('Follow', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_follow_follower'), ['follower_id'], unique=False) + batch_op.create_index(batch_op.f('idx_follow_followed'), ['followed_id'], unique=False) + + op.create_table('User', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('username', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('full_name', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('email', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('hashed_password', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('google_id', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('role', sa.VARCHAR(), server_default=sa.text("'user'::character varying"), autoincrement=False, nullable=False), + sa.Column('is_premium', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True), + sa.Column('is_verified', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True), + sa.Column('is_onboarded', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True), + sa.Column('profile_pic', sa.VARCHAR(), server_default=sa.text("'http://localhost:8000/static/defaults/default_avatar.png'::character varying"), autoincrement=False, nullable=True), + sa.Column('flash_uploads', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('home_uploads', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('bio', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('id', name=op.f('User_pkey')), + sa.UniqueConstraint('email', name=op.f('User_email_key'), postgresql_include=[], postgresql_nulls_not_distinct=False), + sa.UniqueConstraint('google_id', name=op.f('User_google_id_key'), postgresql_include=[], postgresql_nulls_not_distinct=False), + sa.UniqueConstraint('username', name=op.f('User_username_key'), postgresql_include=[], postgresql_nulls_not_distinct=False) + ) + with op.batch_alter_table('User', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_user_username'), ['username'], unique=False) + batch_op.create_index(batch_op.f('idx_user_google_id'), ['google_id'], unique=False) + batch_op.create_index(batch_op.f('idx_user_email'), ['email'], unique=False) + + op.create_table('Video', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('video_url', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('url_480p', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_720p', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_1080p', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_2k', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('url_4k', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('thumbnail_url', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('video_type', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('status', sa.VARCHAR(), server_default=sa.text("'pending'::character varying"), autoincrement=False, nullable=True), + sa.Column('owner_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('views', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('earnings', sa.NUMERIC(precision=10, scale=2), server_default=sa.text('0.0'), autoincrement=False, nullable=True), + sa.Column('shares', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('duration', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=True), + sa.Column('processing_key', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['User.id'], name=op.f('Video_owner_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Video_pkey')) + ) + with op.batch_alter_table('Video', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_video_type'), ['video_type'], unique=False) + batch_op.create_index(batch_op.f('idx_video_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('idx_video_owner'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('idx_video_created'), [sa.literal_column('created_at DESC')], unique=False) + + op.create_table('Repost', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['User.id'], name=op.f('Repost_user_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('Repost_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Repost_pkey')) + ) + with op.batch_alter_table('Repost', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_repost_video'), ['video_id'], unique=False) + batch_op.create_index(batch_op.f('idx_repost_user'), ['user_id'], unique=False) + + op.create_table('Like', + sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['User.id'], name=op.f('Like_user_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('Like_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('user_id', 'video_id', name=op.f('Like_pkey')) + ) + with op.batch_alter_table('Like', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_like_video'), ['video_id'], unique=False) + + op.create_table('Comment', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('content', sa.TEXT(), autoincrement=False, nullable=False), + sa.Column('video_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('owner_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['User.id'], name=op.f('Comment_owner_id_fkey'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['video_id'], ['Video.id'], name=op.f('Comment_video_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Comment_pkey')) + ) + with op.batch_alter_table('Comment', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_comment_video'), ['video_id'], unique=False) + batch_op.create_index(batch_op.f('idx_comment_owner'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('idx_comment_created'), [sa.literal_column('created_at DESC')], unique=False) + + op.create_table('VerificationCode', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('email', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('code', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('expires_at', postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('id', name=op.f('VerificationCode_pkey')) + ) + with op.batch_alter_table('VerificationCode', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_verification_email'), ['email'], unique=False) + + op.create_table('Post', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('content', sa.TEXT(), autoincrement=False, nullable=False), + sa.Column('image_url', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('owner_id', sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column('is_active', sa.BOOLEAN(), server_default=sa.text('true'), autoincrement=False, nullable=True), + sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['User.id'], name=op.f('Post_owner_id_fkey'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('Post_pkey')) + ) + with op.batch_alter_table('Post', schema=None) as batch_op: + batch_op.create_index(batch_op.f('idx_post_owner'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('idx_post_created'), [sa.literal_column('created_at DESC')], unique=False) + + with op.batch_alter_table('settings', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_settings_key')) + + op.drop_table('settings') + # ### end Alembic commands ### diff --git a/alembic/versions/7170f10590dc_initial_migration.py b/alembic/versions/7170f10590dc_initial_migration.py new file mode 100644 index 0000000000000000000000000000000000000000..ae434bbf4eeb4a78401f2aaf7db68ed0e60b36c7 --- /dev/null +++ b/alembic/versions/7170f10590dc_initial_migration.py @@ -0,0 +1,251 @@ +"""initial_migration + +Revision ID: 7170f10590dc +Revises: +Create Date: 2026-02-19 17:29:05.238728 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '7170f10590dc' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # --- users table --- + op.create_table( + 'users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('username', sa.String(), nullable=True), + sa.Column('full_name', sa.String(), nullable=True), + sa.Column('email', sa.String(), nullable=True), + sa.Column('hashed_password', sa.String(), nullable=True), + sa.Column('google_id', sa.String(), nullable=True), + sa.Column('role', sa.String(), nullable=True), + sa.Column('is_premium', sa.Boolean(), nullable=True), + sa.Column('is_verified', sa.Boolean(), nullable=True), + sa.Column('is_onboarded', sa.Boolean(), nullable=True), + sa.Column('profile_pic', sa.String(), nullable=True), + sa.Column('interests', sa.Text(), nullable=True), + sa.Column('referral_source', sa.String(), nullable=True), + sa.Column('goals', sa.Text(), nullable=True), + sa.Column('flash_uploads', sa.Integer(), nullable=True), + sa.Column('home_uploads', sa.Integer(), nullable=True), + sa.Column('bio', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + + # --- verification_codes table --- + op.create_table( + 'verification_codes', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(), nullable=True), + sa.Column('code', sa.String(), nullable=True), + sa.Column('expires_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_verification_codes_email'), 'verification_codes', ['email'], unique=False) + op.create_index(op.f('ix_verification_codes_id'), 'verification_codes', ['id'], unique=False) + + # --- videos table --- + op.create_table( + 'videos', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('video_url', sa.String(), nullable=True), + sa.Column('url_480p', sa.String(), nullable=True), + sa.Column('url_720p', sa.String(), nullable=True), + sa.Column('url_1080p', sa.String(), nullable=True), + sa.Column('url_2k', sa.String(), nullable=True), + sa.Column('url_4k', sa.String(), nullable=True), + sa.Column('thumbnail_url', sa.String(), nullable=True), + sa.Column('video_type', sa.String(), nullable=True), + sa.Column('status', sa.String(), nullable=True), + sa.Column('owner_id', sa.Integer(), nullable=True), + sa.Column('views', sa.Integer(), nullable=True), + sa.Column('earnings', sa.Float(), nullable=True), + sa.Column('shares', sa.Integer(), nullable=True), + sa.Column('duration', sa.Integer(), nullable=True), + sa.Column('processing_key', sa.String(), nullable=True), + sa.Column('tags', sa.Text(), nullable=True), + sa.Column('discovery_score', sa.Float(), nullable=True), + sa.Column('last_owner_interaction_at', sa.DateTime(), nullable=True), + sa.Column('failed_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_videos_id'), 'videos', ['id'], unique=False) + + # --- posts table --- + op.create_table( + 'posts', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('image_url', sa.String(), nullable=True), + sa.Column('owner_id', sa.Integer(), nullable=True), + sa.Column('original_post_id', sa.Integer(), nullable=True), + sa.Column('views_count', sa.Integer(), nullable=True), + sa.Column('tags', sa.Text(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('discovery_score', sa.Float(), nullable=True), + sa.Column('last_owner_interaction_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['original_post_id'], ['posts.id'], ), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_posts_id'), 'posts', ['id'], unique=False) + + # --- views table --- + op.create_table( + 'views', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('post_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_views_id'), 'views', ['id'], unique=False) + + # --- likes table --- + op.create_table( + 'likes', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('post_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_likes_id'), 'likes', ['id'], unique=False) + + # --- comments table --- + op.create_table( + 'comments', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('post_id', sa.Integer(), nullable=True), + sa.Column('parent_id', sa.Integer(), nullable=True), + sa.Column('owner_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['parent_id'], ['comments.id'], ), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_comments_id'), 'comments', ['id'], unique=False) + + # --- follows table --- + op.create_table( + 'follows', + sa.Column('follower_id', sa.Integer(), nullable=False), + sa.Column('followed_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('follower_id', 'followed_id') + ) + + # --- reposts table --- + op.create_table( + 'reposts', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_reposts_id'), 'reposts', ['id'], unique=False) + + # --- achievements table --- + op.create_table( + 'achievements', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('milestone_name', sa.String(), nullable=True), + sa.Column('reached_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_achievements_id'), 'achievements', ['id'], unique=False) + + # --- sponsored_ads table --- + op.create_table( + 'sponsored_ads', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('image_url', sa.String(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_sponsored_ads_id'), 'sponsored_ads', ['id'], unique=False) + + # --- notifications table --- + op.create_table( + 'notifications', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('message', sa.String(), nullable=True), + sa.Column('link', sa.String(), nullable=True), + sa.Column('type', sa.String(), nullable=True), + sa.Column('is_read', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_notifications_id'), 'notifications', ['id'], unique=False) + + # --- push_subscriptions table --- + op.create_table( + 'push_subscriptions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('endpoint', sa.String(), nullable=True), + sa.Column('p256dh', sa.String(), nullable=True), + sa.Column('auth', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_push_subscriptions_endpoint'), 'push_subscriptions', ['endpoint'], unique=True) + op.create_index(op.f('ix_push_subscriptions_id'), 'push_subscriptions', ['id'], unique=False) + + +def downgrade() -> None: + op.drop_table('push_subscriptions') + op.drop_table('notifications') + op.drop_table('sponsored_ads') + op.drop_table('achievements') + op.drop_table('reposts') + op.drop_table('follows') + op.drop_table('comments') + op.drop_table('likes') + op.drop_table('views') + op.drop_table('posts') + op.drop_table('videos') + op.drop_table('verification_codes') + op.drop_table('users') diff --git a/alembic/versions/7acd76e1bfde_add_library_tables_manual.py b/alembic/versions/7acd76e1bfde_add_library_tables_manual.py new file mode 100644 index 0000000000000000000000000000000000000000..a791b4f78cc69ab07c0bc30f134513324a068122 --- /dev/null +++ b/alembic/versions/7acd76e1bfde_add_library_tables_manual.py @@ -0,0 +1,67 @@ +"""Add library tables manual + +Revision ID: 7acd76e1bfde +Revises: f463c2bc4dcf +Create Date: 2026-05-12 21:07:41.449114 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '7acd76e1bfde' +down_revision: Union[str, Sequence[str], None] = 'f463c2bc4dcf' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +from sqlalchemy.dialects import postgresql + +def upgrade() -> None: + """Upgrade schema.""" + # Watch History + op.create_table( + 'watch_history', + sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), + sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False), + sa.Column('video_id', sa.Integer(), sa.ForeignKey('videos.id', ondelete='CASCADE'), nullable=False), + sa.Column('watched_at', sa.DateTime(timezone=True), server_default=sa.func.now(), onupdate=sa.func.now()), + sa.Column('progress_seconds', sa.Integer(), server_default='0'), + sa.Column('duration_seconds', sa.Integer(), server_default='0'), + sa.Column('is_completed', sa.Boolean(), server_default='false') + ) + op.create_index('ix_history_user_id', 'watch_history', ['user_id']) + + # Watch Later + op.create_table( + 'library_watch_later', + sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), + sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False), + sa.Column('video_id', sa.Integer(), sa.ForeignKey('videos.id', ondelete='CASCADE'), nullable=False), + sa.Column('saved_at', sa.DateTime(timezone=True), server_default=sa.func.now()) + ) + op.create_index('ix_watchlater_user_id', 'library_watch_later', ['user_id']) + + # Liked Videos + op.create_table( + 'liked_videos', + sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), + sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False), + sa.Column('video_id', sa.Integer(), sa.ForeignKey('videos.id', ondelete='CASCADE'), nullable=False), + sa.Column('liked_at', sa.DateTime(timezone=True), server_default=sa.func.now()) + ) + op.create_index('ix_liked_user_id', 'liked_videos', ['user_id']) + + +def downgrade() -> None: + """Downgrade schema.""" + op.drop_index('ix_liked_user_id', table_name='liked_videos') + op.drop_table('liked_videos') + op.drop_index('ix_watchlater_user_id', table_name='library_watch_later') + op.drop_table('library_watch_later') + op.drop_index('ix_history_user_id', table_name='watch_history') + op.drop_table('watch_history') + diff --git a/alembic/versions/7c01ead0ba2b_add_wrapped_keys.py b/alembic/versions/7c01ead0ba2b_add_wrapped_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..117a30594238c30235f08e1b06acce6c6090edb5 --- /dev/null +++ b/alembic/versions/7c01ead0ba2b_add_wrapped_keys.py @@ -0,0 +1,34 @@ +"""add_wrapped_keys + +Revision ID: 7c01ead0ba2b +Revises: d377d4ec5352 +Create Date: 2026-02-22 11:57:38.387351 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '7c01ead0ba2b' +down_revision: Union[str, Sequence[str], None] = 'd377d4ec5352' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('chat_messages', sa.Column('recipient_key', sa.Text(), nullable=True)) + op.add_column('chat_messages', sa.Column('sender_key', sa.Text(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('chat_messages', 'sender_key') + op.drop_column('chat_messages', 'recipient_key') + # ### end Alembic commands ### diff --git a/alembic/versions/7cb96200572b_add_pinned_video_id_to_users.py b/alembic/versions/7cb96200572b_add_pinned_video_id_to_users.py new file mode 100644 index 0000000000000000000000000000000000000000..17607055e399920ed983cc6f6f332364ab3b2f87 --- /dev/null +++ b/alembic/versions/7cb96200572b_add_pinned_video_id_to_users.py @@ -0,0 +1,38 @@ +"""add pinned_video_id to users + +Revision ID: 7cb96200572b +Revises: 219cc7d232b2 +Create Date: 2026-04-16 03:08:05.660103 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '7cb96200572b' +down_revision: Union[str, Sequence[str], None] = '219cc7d232b2' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.add_column(sa.Column('pinned_video_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'videos', ['pinned_video_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('pinned_video_id') + + # ### end Alembic commands ### diff --git a/alembic/versions/7e1a2b3c4d5e_performance_indices.py b/alembic/versions/7e1a2b3c4d5e_performance_indices.py new file mode 100644 index 0000000000000000000000000000000000000000..668815c7553effca6f08641054b4a76c07cae674 --- /dev/null +++ b/alembic/versions/7e1a2b3c4d5e_performance_indices.py @@ -0,0 +1,40 @@ +"""performance indices + +Revision ID: 7e1a2b3c4d5e +Revises: 7acd76e1bfde +Create Date: 2026-05-12 21:30:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = '7e1a2b3c4d5e' +down_revision = '7acd76e1bfde' +branch_labels = None +depends_on = None + +def upgrade(): + # Video performance indices + op.create_index('idx_videos_created_at_desc', 'videos', [sa.text('created_at DESC')]) + op.create_index('idx_videos_views_desc', 'videos', [sa.text('views DESC')]) + # op.create_index('idx_videos_category_created', 'videos', ['category', sa.text('created_at DESC')]) + + # Comments optimization + op.create_index('idx_comments_video_id_created', 'comments', ['video_id', sa.text('created_at DESC')]) + + # Interaction performance + op.create_index('idx_likes_video_id', 'likes', ['video_id']) + op.create_index('idx_views_video_id', 'views', ['video_id']) + + # User activity + op.create_index('idx_watch_history_user_watched', 'watch_history', ['user_id', sa.text('watched_at DESC')]) + +def downgrade(): + op.drop_index('idx_videos_created_at_desc', table_name='videos') + op.drop_index('idx_videos_views_desc', table_name='videos') + op.drop_index('idx_videos_category_created', table_name='videos') + op.drop_index('idx_comments_video_id_created', table_name='comments') + op.drop_index('idx_likes_video_id', table_name='likes') + op.drop_index('idx_views_video_id', table_name='views') + op.drop_index('idx_watch_history_user_watched', table_name='watch_history') diff --git a/alembic/versions/806aa527dfad_add_status_to_transaction.py b/alembic/versions/806aa527dfad_add_status_to_transaction.py new file mode 100644 index 0000000000000000000000000000000000000000..d16d7e37d8459b44b801e64662b2d613ac51c9a4 --- /dev/null +++ b/alembic/versions/806aa527dfad_add_status_to_transaction.py @@ -0,0 +1,422 @@ +"""Add status to Transaction + +Revision ID: 806aa527dfad +Revises: 7e1a2b3c4d5e +Create Date: 2026-05-15 22:20:56.665701 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '806aa527dfad' +down_revision: Union[str, Sequence[str], None] = '7e1a2b3c4d5e' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('watch_later', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('watch_later', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_watch_later_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_watch_later_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_watch_later_video_id'), ['video_id'], unique=False) + + with op.batch_alter_table('achievements', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_achievements_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + + with op.batch_alter_table('challenge_entries', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_challenge_entries_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'videos', ['video_id'], ['id']) + batch_op.create_foreign_key(None, 'challenges', ['challenge_id'], ['id']) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + + with op.batch_alter_table('challenges', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_challenges_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_challenges_title'), ['title'], unique=False) + + with op.batch_alter_table('chat_messages', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_chat_messages_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['sender_id'], ['id']) + batch_op.create_foreign_key(None, 'conversations', ['conversation_id'], ['id']) + + with op.batch_alter_table('comments', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('idx_comments_video_id_created')) + batch_op.create_index(batch_op.f('ix_comments_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_comments_owner_id'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('ix_comments_parent_id'), ['parent_id'], unique=False) + batch_op.create_index(batch_op.f('ix_comments_post_id'), ['post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_comments_video_id'), ['video_id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['owner_id'], ['id']) + batch_op.create_foreign_key(None, 'comments', ['parent_id'], ['id']) + batch_op.create_foreign_key(None, 'posts', ['post_id'], ['id']) + batch_op.create_foreign_key(None, 'videos', ['video_id'], ['id']) + + with op.batch_alter_table('conversations', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_conversations_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user1_id'], ['id']) + batch_op.create_foreign_key(None, 'users', ['user2_id'], ['id']) + + with op.batch_alter_table('discovered_categories', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_discovered_categories_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_discovered_categories_is_approved'), ['is_approved'], unique=False) + batch_op.create_index(batch_op.f('ix_discovered_categories_name'), ['name'], unique=True) + + with op.batch_alter_table('follows', schema=None) as batch_op: + batch_op.alter_column('follower_id', + existing_type=sa.INTEGER(), + nullable=True) + batch_op.alter_column('following_id', + existing_type=sa.INTEGER(), + nullable=True) + batch_op.drop_index(batch_op.f('idx_follows_follower_id')) + batch_op.drop_index(batch_op.f('idx_follows_following_id')) + batch_op.create_index(batch_op.f('ix_follows_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_follows_follower_id'), ['follower_id'], unique=False) + batch_op.create_index(batch_op.f('ix_follows_following_id'), ['following_id'], unique=False) + batch_op.create_index(batch_op.f('ix_follows_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['following_id'], ['id']) + batch_op.create_foreign_key(None, 'users', ['follower_id'], ['id']) + + with op.batch_alter_table('likes', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('idx_likes_video_id')) + batch_op.create_index(batch_op.f('ix_likes_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_likes_post_id'), ['post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_likes_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_likes_video_id'), ['video_id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + batch_op.create_foreign_key(None, 'posts', ['post_id'], ['id']) + batch_op.create_foreign_key(None, 'videos', ['video_id'], ['id']) + + with op.batch_alter_table('notifications', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_notifications_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + + with op.batch_alter_table('partner_leads', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_partner_leads_brand_name'), ['brand_name'], unique=False) + batch_op.create_index(batch_op.f('ix_partner_leads_contact_email'), ['contact_email'], unique=False) + batch_op.create_index(batch_op.f('ix_partner_leads_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_partner_leads_id'), ['id'], unique=False) + + with op.batch_alter_table('payout_requests', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_payout_requests_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_requested_at'), ['requested_at'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_wallet_id'), ['wallet_id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + batch_op.create_foreign_key(None, 'wallets', ['wallet_id'], ['id']) + + with op.batch_alter_table('posts', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('idx_posts_owner_id')) + batch_op.create_index(batch_op.f('ix_posts_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_posts_discovery_score'), ['discovery_score'], unique=False) + batch_op.create_index(batch_op.f('ix_posts_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_posts_original_post_id'), ['original_post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_posts_owner_id'), ['owner_id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['owner_id'], ['id']) + batch_op.create_foreign_key(None, 'posts', ['original_post_id'], ['id']) + + with op.batch_alter_table('push_subscriptions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_push_subscriptions_endpoint'), ['endpoint'], unique=True) + batch_op.create_index(batch_op.f('ix_push_subscriptions_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + + with op.batch_alter_table('reposts', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_reposts_id'), ['id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + batch_op.create_foreign_key(None, 'videos', ['video_id'], ['id']) + + with op.batch_alter_table('settings', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_settings_key'), ['key'], unique=False) + + with op.batch_alter_table('sponsored_ads', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_sponsored_ads_id'), ['id'], unique=False) + + with op.batch_alter_table('transactions', schema=None) as batch_op: + batch_op.add_column(sa.Column('status', sa.String(), nullable=True)) + batch_op.create_index(batch_op.f('ix_transactions_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_reference_id'), ['reference_id'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_transaction_type'), ['transaction_type'], unique=False) + batch_op.create_index(batch_op.f('ix_transactions_wallet_id'), ['wallet_id'], unique=False) + batch_op.create_foreign_key(None, 'wallets', ['wallet_id'], ['id']) + + with op.batch_alter_table('user_recommendation_profiles', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_user_recommendation_profiles_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_user_recommendation_profiles_user_id'), ['user_id'], unique=True) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + + with op.batch_alter_table('user_sessions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_user_sessions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_user_sessions_token_hash'), ['token_hash'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_users_country'), ['country'], unique=False) + batch_op.create_index(batch_op.f('ix_users_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_users_email'), ['email'], unique=True) + batch_op.create_index(batch_op.f('ix_users_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_users_username'), ['username'], unique=True) + batch_op.create_unique_constraint(None, ['google_id']) + batch_op.create_foreign_key(None, 'videos', ['pinned_video_id'], ['id']) + + with op.batch_alter_table('verification_codes', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_verification_codes_email'), ['email'], unique=False) + batch_op.create_index(batch_op.f('ix_verification_codes_id'), ['id'], unique=False) + + with op.batch_alter_table('video_interactions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_video_interactions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_video_interactions_timestamp'), ['timestamp'], unique=False) + batch_op.create_index(batch_op.f('ix_video_interactions_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_video_interactions_video_id'), ['video_id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + batch_op.create_foreign_key(None, 'videos', ['video_id'], ['id']) + + with op.batch_alter_table('videos', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('idx_videos_created_at_desc')) + batch_op.drop_index(batch_op.f('idx_videos_discovery_score')) + batch_op.drop_index(batch_op.f('idx_videos_owner_id')) + batch_op.drop_index(batch_op.f('idx_videos_views_desc')) + batch_op.create_index(batch_op.f('ix_videos_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_discovery_score'), ['discovery_score'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_owner_id'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_video_type'), ['video_type'], unique=False) + batch_op.create_foreign_key(None, 'users', ['owner_id'], ['id']) + + with op.batch_alter_table('views', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('idx_views_video_id')) + batch_op.create_index(batch_op.f('ix_views_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_views_post_id'), ['post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_views_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_views_video_id'), ['video_id'], unique=False) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + batch_op.create_foreign_key(None, 'posts', ['post_id'], ['id']) + batch_op.create_foreign_key(None, 'videos', ['video_id'], ['id']) + + with op.batch_alter_table('wallets', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_wallets_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_wallets_user_id'), ['user_id'], unique=True) + batch_op.create_foreign_key(None, 'users', ['user_id'], ['id']) + + with op.batch_alter_table('watch_history', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('idx_watch_history_user_watched')) + batch_op.create_index('ix_history_user_time', ['user_id', 'watched_at'], unique=False) + batch_op.create_index('ix_history_video_id', ['video_id'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('watch_history', schema=None) as batch_op: + batch_op.drop_index('ix_history_video_id') + batch_op.drop_index('ix_history_user_time') + batch_op.create_index(batch_op.f('idx_watch_history_user_watched'), ['user_id', sa.literal_column('watched_at DESC')], unique=False) + + with op.batch_alter_table('wallets', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_wallets_user_id')) + batch_op.drop_index(batch_op.f('ix_wallets_id')) + + with op.batch_alter_table('views', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_views_video_id')) + batch_op.drop_index(batch_op.f('ix_views_user_id')) + batch_op.drop_index(batch_op.f('ix_views_post_id')) + batch_op.drop_index(batch_op.f('ix_views_id')) + batch_op.create_index(batch_op.f('idx_views_video_id'), ['video_id'], unique=False) + + with op.batch_alter_table('videos', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_videos_video_type')) + batch_op.drop_index(batch_op.f('ix_videos_status')) + batch_op.drop_index(batch_op.f('ix_videos_owner_id')) + batch_op.drop_index(batch_op.f('ix_videos_id')) + batch_op.drop_index(batch_op.f('ix_videos_discovery_score')) + batch_op.drop_index(batch_op.f('ix_videos_created_at')) + batch_op.create_index(batch_op.f('idx_videos_views_desc'), [sa.literal_column('views DESC')], unique=False) + batch_op.create_index(batch_op.f('idx_videos_owner_id'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('idx_videos_discovery_score'), ['discovery_score'], unique=False) + batch_op.create_index(batch_op.f('idx_videos_created_at_desc'), [sa.literal_column('created_at DESC')], unique=False) + + with op.batch_alter_table('video_interactions', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_video_interactions_video_id')) + batch_op.drop_index(batch_op.f('ix_video_interactions_user_id')) + batch_op.drop_index(batch_op.f('ix_video_interactions_timestamp')) + batch_op.drop_index(batch_op.f('ix_video_interactions_id')) + + with op.batch_alter_table('verification_codes', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_verification_codes_id')) + batch_op.drop_index(batch_op.f('ix_verification_codes_email')) + + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='unique') + batch_op.drop_index(batch_op.f('ix_users_username')) + batch_op.drop_index(batch_op.f('ix_users_id')) + batch_op.drop_index(batch_op.f('ix_users_email')) + batch_op.drop_index(batch_op.f('ix_users_created_at')) + batch_op.drop_index(batch_op.f('ix_users_country')) + + with op.batch_alter_table('user_sessions', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_user_sessions_token_hash')) + batch_op.drop_index(batch_op.f('ix_user_sessions_id')) + + with op.batch_alter_table('user_recommendation_profiles', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_user_recommendation_profiles_user_id')) + batch_op.drop_index(batch_op.f('ix_user_recommendation_profiles_id')) + + with op.batch_alter_table('transactions', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_transactions_wallet_id')) + batch_op.drop_index(batch_op.f('ix_transactions_transaction_type')) + batch_op.drop_index(batch_op.f('ix_transactions_status')) + batch_op.drop_index(batch_op.f('ix_transactions_reference_id')) + batch_op.drop_index(batch_op.f('ix_transactions_id')) + batch_op.drop_index(batch_op.f('ix_transactions_created_at')) + batch_op.drop_column('status') + + with op.batch_alter_table('sponsored_ads', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_sponsored_ads_id')) + + with op.batch_alter_table('settings', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_settings_key')) + + with op.batch_alter_table('reposts', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_reposts_id')) + + with op.batch_alter_table('push_subscriptions', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_push_subscriptions_id')) + batch_op.drop_index(batch_op.f('ix_push_subscriptions_endpoint')) + + with op.batch_alter_table('posts', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_posts_owner_id')) + batch_op.drop_index(batch_op.f('ix_posts_original_post_id')) + batch_op.drop_index(batch_op.f('ix_posts_id')) + batch_op.drop_index(batch_op.f('ix_posts_discovery_score')) + batch_op.drop_index(batch_op.f('ix_posts_created_at')) + batch_op.create_index(batch_op.f('idx_posts_owner_id'), ['owner_id'], unique=False) + + with op.batch_alter_table('payout_requests', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_payout_requests_wallet_id')) + batch_op.drop_index(batch_op.f('ix_payout_requests_user_id')) + batch_op.drop_index(batch_op.f('ix_payout_requests_status')) + batch_op.drop_index(batch_op.f('ix_payout_requests_requested_at')) + batch_op.drop_index(batch_op.f('ix_payout_requests_id')) + + with op.batch_alter_table('partner_leads', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_partner_leads_id')) + batch_op.drop_index(batch_op.f('ix_partner_leads_created_at')) + batch_op.drop_index(batch_op.f('ix_partner_leads_contact_email')) + batch_op.drop_index(batch_op.f('ix_partner_leads_brand_name')) + + with op.batch_alter_table('notifications', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_notifications_id')) + + with op.batch_alter_table('likes', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_likes_video_id')) + batch_op.drop_index(batch_op.f('ix_likes_user_id')) + batch_op.drop_index(batch_op.f('ix_likes_post_id')) + batch_op.drop_index(batch_op.f('ix_likes_id')) + batch_op.create_index(batch_op.f('idx_likes_video_id'), ['video_id'], unique=False) + + with op.batch_alter_table('follows', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_follows_id')) + batch_op.drop_index(batch_op.f('ix_follows_following_id')) + batch_op.drop_index(batch_op.f('ix_follows_follower_id')) + batch_op.drop_index(batch_op.f('ix_follows_created_at')) + batch_op.create_index(batch_op.f('idx_follows_following_id'), ['following_id'], unique=False) + batch_op.create_index(batch_op.f('idx_follows_follower_id'), ['follower_id'], unique=False) + batch_op.alter_column('following_id', + existing_type=sa.INTEGER(), + nullable=False) + batch_op.alter_column('follower_id', + existing_type=sa.INTEGER(), + nullable=False) + + with op.batch_alter_table('discovered_categories', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_discovered_categories_name')) + batch_op.drop_index(batch_op.f('ix_discovered_categories_is_approved')) + batch_op.drop_index(batch_op.f('ix_discovered_categories_id')) + + with op.batch_alter_table('conversations', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_conversations_id')) + + with op.batch_alter_table('comments', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_comments_video_id')) + batch_op.drop_index(batch_op.f('ix_comments_post_id')) + batch_op.drop_index(batch_op.f('ix_comments_parent_id')) + batch_op.drop_index(batch_op.f('ix_comments_owner_id')) + batch_op.drop_index(batch_op.f('ix_comments_id')) + batch_op.create_index(batch_op.f('idx_comments_video_id_created'), ['video_id', sa.literal_column('created_at DESC')], unique=False) + + with op.batch_alter_table('chat_messages', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_chat_messages_id')) + + with op.batch_alter_table('challenges', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_challenges_title')) + batch_op.drop_index(batch_op.f('ix_challenges_id')) + + with op.batch_alter_table('challenge_entries', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_challenge_entries_id')) + + with op.batch_alter_table('achievements', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_index(batch_op.f('ix_achievements_id')) + + with op.batch_alter_table('watch_later', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_watch_later_video_id')) + batch_op.drop_index(batch_op.f('ix_watch_later_user_id')) + batch_op.drop_index(batch_op.f('ix_watch_later_id')) + + op.drop_table('watch_later') + # ### end Alembic commands ### diff --git a/alembic/versions/87f6c7656bb5_add_payout_requests_table.py b/alembic/versions/87f6c7656bb5_add_payout_requests_table.py new file mode 100644 index 0000000000000000000000000000000000000000..4ba9ae99c1aed6f8d64a826f991953c5f8f28599 --- /dev/null +++ b/alembic/versions/87f6c7656bb5_add_payout_requests_table.py @@ -0,0 +1,59 @@ +"""Add payout requests table + +Revision ID: 87f6c7656bb5 +Revises: 2e5874e941aa +Create Date: 2026-04-07 00:46:05.884885 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '87f6c7656bb5' +down_revision: Union[str, Sequence[str], None] = '2e5874e941aa' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('payout_requests', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('wallet_id', sa.Integer(), nullable=True), + sa.Column('amount', sa.Numeric(precision=12, scale=2), nullable=True), + sa.Column('status', sa.String(), nullable=True), + sa.Column('bank_details', sa.Text(), nullable=True), + sa.Column('admin_note', sa.Text(), nullable=True), + sa.Column('requested_at', sa.DateTime(), nullable=True), + sa.Column('processed_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['wallet_id'], ['wallets.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('payout_requests', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_payout_requests_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_requested_at'), ['requested_at'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_payout_requests_wallet_id'), ['wallet_id'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('payout_requests', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_payout_requests_wallet_id')) + batch_op.drop_index(batch_op.f('ix_payout_requests_user_id')) + batch_op.drop_index(batch_op.f('ix_payout_requests_status')) + batch_op.drop_index(batch_op.f('ix_payout_requests_requested_at')) + batch_op.drop_index(batch_op.f('ix_payout_requests_id')) + + op.drop_table('payout_requests') + # ### end Alembic commands ### diff --git a/alembic/versions/abdefa368e36_add_missing_columns_to_users.py b/alembic/versions/abdefa368e36_add_missing_columns_to_users.py new file mode 100644 index 0000000000000000000000000000000000000000..dfb2eb2173565f43de77c535376b7fa98396bcc6 --- /dev/null +++ b/alembic/versions/abdefa368e36_add_missing_columns_to_users.py @@ -0,0 +1,38 @@ +"""Add missing columns to users + +Revision ID: abdefa368e36 +Revises: 7cb96200572b +Create Date: 2026-04-28 10:24:45.757115 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'abdefa368e36' +down_revision: Union[str, Sequence[str], None] = '7cb96200572b' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.add_column(sa.Column('country', sa.String(), nullable=True)) + batch_op.create_index(batch_op.f('ix_users_country'), ['country'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_users_country')) + batch_op.drop_column('country') + + # ### end Alembic commands ### diff --git a/alembic/versions/b1506accc1d5_add_recommendation_engine_tables.py b/alembic/versions/b1506accc1d5_add_recommendation_engine_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..21b9d755978050146cbcb074f198ca12fa99f5d1 --- /dev/null +++ b/alembic/versions/b1506accc1d5_add_recommendation_engine_tables.py @@ -0,0 +1,109 @@ +"""add_recommendation_engine_tables + +Revision ID: b1506accc1d5 +Revises: 3a5babf76aab +Create Date: 2026-04-16 02:01:24.405765 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = 'b1506accc1d5' +down_revision: Union[str, Sequence[str], None] = '3a5babf76aab' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('user_recommendation_profiles', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('tag_affinity', sa.Text(), nullable=True), + sa.Column('seen_video_ids', sa.Text(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('user_recommendation_profiles', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_user_recommendation_profiles_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_user_recommendation_profiles_user_id'), ['user_id'], unique=True) + + op.create_table('video_interactions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('video_id', sa.Integer(), nullable=False), + sa.Column('watch_time', sa.Float(), nullable=True), + sa.Column('duration', sa.Float(), nullable=True), + sa.Column('liked', sa.Boolean(), nullable=True), + sa.Column('skipped', sa.Boolean(), nullable=True), + sa.Column('replayed', sa.Boolean(), nullable=True), + sa.Column('completion_rate', sa.Float(), nullable=True), + sa.Column('skipped_fast', sa.Boolean(), nullable=True), + sa.Column('interaction_score', sa.Float(), nullable=True), + sa.Column('timestamp', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('video_interactions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_video_interactions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_video_interactions_timestamp'), ['timestamp'], unique=False) + batch_op.create_index(batch_op.f('ix_video_interactions_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_video_interactions_video_id'), ['video_id'], unique=False) + + with op.batch_alter_table('subscriptions', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_subscriptions_creator_id')) + batch_op.drop_index(batch_op.f('ix_subscriptions_id')) + batch_op.drop_index(batch_op.f('ix_subscriptions_status')) + batch_op.drop_index(batch_op.f('ix_subscriptions_subscriber_id')) + + op.drop_table('subscriptions') + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_users_created_at'), ['created_at'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_users_created_at')) + + op.create_table('subscriptions', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('subscriber_id', sa.INTEGER(), autoincrement=False, nullable=True), + sa.Column('creator_id', sa.INTEGER(), autoincrement=False, nullable=True), + sa.Column('monthly_price', sa.NUMERIC(precision=12, scale=2), autoincrement=False, nullable=True), + sa.Column('status', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('next_billing_date', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), + sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), + sa.ForeignKeyConstraint(['creator_id'], ['users.id'], name=op.f('subscriptions_creator_id_fkey')), + sa.ForeignKeyConstraint(['subscriber_id'], ['users.id'], name=op.f('subscriptions_subscriber_id_fkey')), + sa.PrimaryKeyConstraint('id', name=op.f('subscriptions_pkey')) + ) + with op.batch_alter_table('subscriptions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_subscriptions_subscriber_id'), ['subscriber_id'], unique=False) + batch_op.create_index(batch_op.f('ix_subscriptions_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('ix_subscriptions_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_subscriptions_creator_id'), ['creator_id'], unique=False) + + with op.batch_alter_table('video_interactions', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_video_interactions_video_id')) + batch_op.drop_index(batch_op.f('ix_video_interactions_user_id')) + batch_op.drop_index(batch_op.f('ix_video_interactions_timestamp')) + batch_op.drop_index(batch_op.f('ix_video_interactions_id')) + + op.drop_table('video_interactions') + with op.batch_alter_table('user_recommendation_profiles', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_user_recommendation_profiles_user_id')) + batch_op.drop_index(batch_op.f('ix_user_recommendation_profiles_id')) + + op.drop_table('user_recommendation_profiles') + # ### end Alembic commands ### diff --git a/alembic/versions/beb747f01187_add_brand_and_start_date_to_challenges.py b/alembic/versions/beb747f01187_add_brand_and_start_date_to_challenges.py new file mode 100644 index 0000000000000000000000000000000000000000..41d65b8e58fe45d6ffecfb4c63057667a7dafb87 --- /dev/null +++ b/alembic/versions/beb747f01187_add_brand_and_start_date_to_challenges.py @@ -0,0 +1,29 @@ +"""add brand and start_date to challenges + +Revision ID: beb747f01187 +Revises: ed2ee0262d0d +Create Date: 2026-04-05 20:52:13.272148 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'beb747f01187' +down_revision: Union[str, Sequence[str], None] = 'ed2ee0262d0d' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Safely add columns to challenges table + op.add_column('challenges', sa.Column('brand', sa.String(), nullable=True)) + op.add_column('challenges', sa.Column('start_date', sa.DateTime(), nullable=True)) + + +def downgrade() -> None: + op.drop_column('challenges', 'start_date') + op.drop_column('challenges', 'brand') diff --git a/alembic/versions/c6b4627fe974_add_winner_fields_to_challenges.py b/alembic/versions/c6b4627fe974_add_winner_fields_to_challenges.py new file mode 100644 index 0000000000000000000000000000000000000000..464943b52be9aceb6f0472ab425152b920030720 --- /dev/null +++ b/alembic/versions/c6b4627fe974_add_winner_fields_to_challenges.py @@ -0,0 +1,29 @@ +"""add winner fields to challenges + +Revision ID: c6b4627fe974 +Revises: beb747f01187 +Create Date: 2026-04-05 21:16:46.679501 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'c6b4627fe974' +down_revision: Union[str, Sequence[str], None] = 'beb747f01187' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Safely add columns + op.add_column('challenge_entries', sa.Column('is_winner', sa.Boolean(), nullable=True, server_default='false')) + op.add_column('challenges', sa.Column('winner_picked', sa.Boolean(), nullable=True, server_default='false')) + + +def downgrade() -> None: + op.drop_column('challenges', 'winner_picked') + op.drop_column('challenge_entries', 'is_winner') diff --git a/alembic/versions/d377d4ec5352_add_chat_models.py b/alembic/versions/d377d4ec5352_add_chat_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c594161119f0c56fa0af7a41549560e93fc4bac6 --- /dev/null +++ b/alembic/versions/d377d4ec5352_add_chat_models.py @@ -0,0 +1,60 @@ +"""add_chat_models + +Revision ID: d377d4ec5352 +Revises: 7170f10590dc +Create Date: 2026-02-22 11:55:47.035836 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'd377d4ec5352' +down_revision: Union[str, Sequence[str], None] = '7170f10590dc' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('conversations', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user1_id', sa.Integer(), nullable=True), + sa.Column('user2_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user1_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['user2_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_conversations_id'), 'conversations', ['id'], unique=False) + op.create_table('chat_messages', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('conversation_id', sa.Integer(), nullable=True), + sa.Column('sender_id', sa.Integer(), nullable=True), + sa.Column('encrypted_content', sa.Text(), nullable=True), + sa.Column('iv', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['conversation_id'], ['conversations.id'], ), + sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_chat_messages_id'), 'chat_messages', ['id'], unique=False) + op.add_column('users', sa.Column('public_key', sa.Text(), nullable=True)) + op.create_unique_constraint(None, 'users', ['google_id']) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'users', type_='unique') + op.drop_column('users', 'public_key') + op.drop_index(op.f('ix_chat_messages_id'), table_name='chat_messages') + op.drop_table('chat_messages') + op.drop_index(op.f('ix_conversations_id'), table_name='conversations') + op.drop_table('conversations') + # ### end Alembic commands ### diff --git a/alembic/versions/de8fb49fe9ad_add_indexes_and_caching_columns_for_.py b/alembic/versions/de8fb49fe9ad_add_indexes_and_caching_columns_for_.py new file mode 100644 index 0000000000000000000000000000000000000000..66516f98903f7018307ebb398a48c2eb2ead837c --- /dev/null +++ b/alembic/versions/de8fb49fe9ad_add_indexes_and_caching_columns_for_.py @@ -0,0 +1,96 @@ +"""Add indexes and caching columns for performance + +Revision ID: de8fb49fe9ad +Revises: 4c7e702c81d7 +Create Date: 2026-04-06 23:22:30.947949 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'de8fb49fe9ad' +down_revision: Union[str, Sequence[str], None] = '4c7e702c81d7' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('comments', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_comments_owner_id'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('ix_comments_parent_id'), ['parent_id'], unique=False) + batch_op.create_index(batch_op.f('ix_comments_post_id'), ['post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_comments_video_id'), ['video_id'], unique=False) + + with op.batch_alter_table('likes', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_likes_post_id'), ['post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_likes_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_likes_video_id'), ['video_id'], unique=False) + + with op.batch_alter_table('posts', schema=None) as batch_op: + batch_op.add_column(sa.Column('likes_count', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('comments_count', sa.Integer(), nullable=True)) + batch_op.create_index(batch_op.f('ix_posts_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_posts_discovery_score'), ['discovery_score'], unique=False) + batch_op.create_index(batch_op.f('ix_posts_original_post_id'), ['original_post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_posts_owner_id'), ['owner_id'], unique=False) + + with op.batch_alter_table('videos', schema=None) as batch_op: + batch_op.add_column(sa.Column('likes_count', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('comments_count', sa.Integer(), nullable=True)) + batch_op.create_index(batch_op.f('ix_videos_created_at'), ['created_at'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_discovery_score'), ['discovery_score'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_owner_id'), ['owner_id'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_status'), ['status'], unique=False) + batch_op.create_index(batch_op.f('ix_videos_video_type'), ['video_type'], unique=False) + + with op.batch_alter_table('views', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_views_post_id'), ['post_id'], unique=False) + batch_op.create_index(batch_op.f('ix_views_user_id'), ['user_id'], unique=False) + batch_op.create_index(batch_op.f('ix_views_video_id'), ['video_id'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('views', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_views_video_id')) + batch_op.drop_index(batch_op.f('ix_views_user_id')) + batch_op.drop_index(batch_op.f('ix_views_post_id')) + + with op.batch_alter_table('videos', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_videos_video_type')) + batch_op.drop_index(batch_op.f('ix_videos_status')) + batch_op.drop_index(batch_op.f('ix_videos_owner_id')) + batch_op.drop_index(batch_op.f('ix_videos_discovery_score')) + batch_op.drop_index(batch_op.f('ix_videos_created_at')) + batch_op.drop_column('comments_count') + batch_op.drop_column('likes_count') + + with op.batch_alter_table('posts', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_posts_owner_id')) + batch_op.drop_index(batch_op.f('ix_posts_original_post_id')) + batch_op.drop_index(batch_op.f('ix_posts_discovery_score')) + batch_op.drop_index(batch_op.f('ix_posts_created_at')) + batch_op.drop_column('comments_count') + batch_op.drop_column('likes_count') + + with op.batch_alter_table('likes', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_likes_video_id')) + batch_op.drop_index(batch_op.f('ix_likes_user_id')) + batch_op.drop_index(batch_op.f('ix_likes_post_id')) + + with op.batch_alter_table('comments', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_comments_video_id')) + batch_op.drop_index(batch_op.f('ix_comments_post_id')) + batch_op.drop_index(batch_op.f('ix_comments_parent_id')) + batch_op.drop_index(batch_op.f('ix_comments_owner_id')) + + # ### end Alembic commands ### diff --git a/alembic/versions/ed2ee0262d0d_add_challenges.py b/alembic/versions/ed2ee0262d0d_add_challenges.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a8aa5a473bc1d8e6f4a09fb8bf6947a5033a0c --- /dev/null +++ b/alembic/versions/ed2ee0262d0d_add_challenges.py @@ -0,0 +1,68 @@ +"""add_challenges + +Revision ID: ed2ee0262d0d +Revises: 6beb84aaed26 +Create Date: 2026-04-05 20:32:10.590141 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'ed2ee0262d0d' +down_revision: Union[str, Sequence[str], None] = '6beb84aaed26' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('challenges', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('prize', sa.String(), nullable=True), + sa.Column('is_open', sa.Boolean(), nullable=True), + sa.Column('end_date', sa.DateTime(), nullable=True), + sa.Column('entry_count', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('challenges', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_challenges_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_challenges_title'), ['title'], unique=False) + + op.create_table('challenge_entries', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('challenge_id', sa.Integer(), nullable=True), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['challenge_id'], ['challenges.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['videos.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('challenge_entries', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_challenge_entries_id'), ['id'], unique=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('challenge_entries', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_challenge_entries_id')) + + op.drop_table('challenge_entries') + with op.batch_alter_table('challenges', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_challenges_title')) + batch_op.drop_index(batch_op.f('ix_challenges_id')) + + op.drop_table('challenges') + # ### end Alembic commands ### diff --git a/alembic/versions/f3b1a2c4e5d6_add_processing_message_to_video.py b/alembic/versions/f3b1a2c4e5d6_add_processing_message_to_video.py new file mode 100644 index 0000000000000000000000000000000000000000..0c0296f047a49c89e1b4fd5c01d9c5ca801b71a3 --- /dev/null +++ b/alembic/versions/f3b1a2c4e5d6_add_processing_message_to_video.py @@ -0,0 +1,24 @@ +"""add processing_message to video + +Revision ID: f3b1a2c4e5d6 +Revises: 87f6c7656bb5 +Create Date: 2026-04-12 17:10:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f3b1a2c4e5d6' +down_revision = '87f6c7656bb5' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column('videos', sa.Column('processing_message', sa.String(), nullable=True)) + + +def downgrade(): + op.drop_column('videos', 'processing_message') diff --git a/alembic/versions/f463c2bc4dcf_add_paid_and_gold_challenge_fields.py b/alembic/versions/f463c2bc4dcf_add_paid_and_gold_challenge_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..c103628eff77769833883df6345f482eabed78dc --- /dev/null +++ b/alembic/versions/f463c2bc4dcf_add_paid_and_gold_challenge_fields.py @@ -0,0 +1,40 @@ +"""add_paid_and_gold_challenge_fields + +Revision ID: f463c2bc4dcf +Revises: 55ef522b3e8c +Create Date: 2026-05-05 21:54:07.267666 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'f463c2bc4dcf' +down_revision: Union[str, Sequence[str], None] = '55ef522b3e8c' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('challenges', schema=None) as batch_op: + batch_op.add_column(sa.Column('is_paid', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('is_gold', sa.Boolean(), nullable=True)) + batch_op.add_column(sa.Column('entry_fee', sa.Numeric(precision=12, scale=2), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('challenges', schema=None) as batch_op: + batch_op.drop_column('entry_fee') + batch_op.drop_column('is_gold') + batch_op.drop_column('is_paid') + + # ### end Alembic commands ### diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/api/v1/api.py b/app/api/v1/api.py new file mode 100644 index 0000000000000000000000000000000000000000..b5902cad367222d8a209981f94b4c62dbd7f9a76 --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,33 @@ +from fastapi import APIRouter +from app.api.v1.endpoints import auth, videos, admin, users, posts, achievements, notifications, ads, chat, challenges, monetization, video_views, seo, recommendations, partners, categories, library, history, watch_later, liked, following, metrics, email, reports, comments + + +api_router = APIRouter() +api_router.include_router(auth.router, prefix="/auth", tags=["auth"]) +api_router.include_router(videos.router, prefix="/videos", tags=["videos"]) +api_router.include_router(admin.router, prefix="/admin", tags=["admin"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(challenges.router, prefix="/challenges", tags=["challenges"]) +api_router.include_router(posts.router, prefix="/posts", tags=["posts"]) +api_router.include_router(achievements.router, prefix="/achievements", tags=["achievements"]) +api_router.include_router(notifications.router, prefix="/notifications", tags=["notifications"]) +api_router.include_router(ads.router, prefix="/ads", tags=["ads"]) +api_router.include_router(video_views.router, prefix="/views", tags=["views"]) +api_router.include_router(seo.router, prefix="/seo", tags=["seo"]) +api_router.include_router(chat.router, prefix="/chat", tags=["chat"]) +api_router.include_router(recommendations.router, prefix="/recommend", tags=["recommendations"]) +api_router.include_router(partners.router, prefix="/partners", tags=["partners"]) +api_router.include_router(categories.router, prefix="/categories", tags=["categories"]) +api_router.include_router(library.router, prefix="/library", tags=["library"]) +api_router.include_router(history.router, prefix="/history", tags=["history"]) +api_router.include_router(watch_later.router, prefix="/watch-later", tags=["watch-later"]) +api_router.include_router(liked.router, prefix="/liked", tags=["liked"]) +api_router.include_router(following.router, prefix="/following", tags=["following"]) +api_router.include_router(monetization.router, prefix="/monetization", tags=["monetization"]) +api_router.include_router(metrics.router, prefix="/metrics", tags=["metrics"]) +api_router.include_router(email.router, prefix="/email", tags=["email"]) +api_router.include_router(reports.router, prefix="/reports", tags=["reports"]) +api_router.include_router(comments.router, prefix="/comments", tags=["comments"]) + + + diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/api/v1/endpoints/achievements.py b/app/api/v1/endpoints/achievements.py new file mode 100644 index 0000000000000000000000000000000000000000..9b473afb4c56e5df2bbe3337a31cb876a73fdab4 --- /dev/null +++ b/app/api/v1/endpoints/achievements.py @@ -0,0 +1,16 @@ +from typing import List +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from app.db.session import get_db +from app.core import dependencies +from app.crud import achievement as crud_achievement +from app.schemas import schemas + +router = APIRouter() + +@router.get("/", response_model=List[schemas.Achievement]) +def read_achievements( + db: Session = Depends(get_db), + current_user: dict = Depends(dependencies.get_current_user) +): + return crud_achievement.get_achievements(db, user_id=current_user.id) diff --git a/app/api/v1/endpoints/admin.py b/app/api/v1/endpoints/admin.py new file mode 100644 index 0000000000000000000000000000000000000000..881506fa8bfdbce463e14ee7251c63bd4b482eeb --- /dev/null +++ b/app/api/v1/endpoints/admin.py @@ -0,0 +1,400 @@ +from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks +from sqlalchemy.orm import Session +from sqlalchemy import func +from app.db.session import get_db +from app.schemas import schemas +from app.core.dependencies import admin_only +from app.core import security, config +from app.crud import user as crud_user, setting as crud_setting +from app.models.models import User, Video, View, Challenge, ChallengeEntry, Transaction, PayoutRequest +from fastapi.security import OAuth2PasswordRequestForm +from datetime import timedelta, datetime +from typing import List, Optional +from sqlalchemy import cast, Date +from app.tasks.email_tasks import queue_new_challenge_announcement +from app.services.email_service import send_pro_upgrade_email + +router = APIRouter() + +@router.post("/login", response_model=schemas.Token) +async def login_for_admin_access_token( + db: Session = Depends(get_db), + form_data: OAuth2PasswordRequestForm = Depends() +): + user = crud_user.get_user_by_username(db, username=form_data.username) + if not user or not security.verify_password(form_data.password, user.hashed_password): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + + if user.role != "admin": + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Access denied: Admin privileges required", + ) + + access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = security.create_access_token( + data={"sub": user.username}, expires_delta=access_token_expires + ) + return {"access_token": access_token, "token_type": "bearer"} + + +@router.get("/users", response_model=List[schemas.User]) +def read_users( + skip: int = 0, + limit: int = 100, + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + users = db.query(User).offset(skip).limit(limit).all() + return users + +@router.get("/stats") +def read_stats( + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + user_count = db.query(func.count(User.id)).scalar() or 0 + video_count = db.query(func.count(Video.id)).scalar() or 0 + premium_count = db.query(func.count(User.id)).filter(User.is_premium == True).scalar() or 0 + + # Sum views + total_views_sum = db.query(func.sum(Video.views)).scalar() or 0 + + # Total Revenue (Subscriptions) + total_rev = db.query(func.sum(Transaction.amount)).filter(Transaction.transaction_type == 'pro_subscription').scalar() or 0 + + # Pending Payouts (Liabilities) + pending_payouts_sum = db.query(func.sum(PayoutRequest.amount)).filter(PayoutRequest.status == 'pending').scalar() or 0 + + # Top Countries Breakdown + top_signup_countries_query = ( + db.query(User.country, func.count(User.id).label("count")) + .filter(User.country != None) + .group_by(User.country) + .order_by(func.count(User.id).desc()) + .limit(5) + .all() + ) + top_signup_countries = [{"country": c, "count": cnt} for c, cnt in top_signup_countries_query] + + return { + "users": user_count, + "videos": video_count, + "premium_users": premium_count, + "total_views": total_views_sum, + "total_revenue": float(total_rev), + "pending_payouts": float(pending_payouts_sum), + "top_signup_countries": top_signup_countries + } + +@router.post("/promote/{user_id}") +def promote_user( + user_id: int, + background_tasks: BackgroundTasks, + is_premium: bool = True, + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + user = crud_user.get_user_by_id(db, user_id=user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + was_premium = user.is_premium + user.is_premium = is_premium + db.commit() + db.refresh(user) + + if is_premium and not was_premium and user.email: + background_tasks.add_task(send_pro_upgrade_email, user.email, user.username) + + return {"message": f"User {user.username} premium status set to {is_premium}"} + +@router.get("/settings/storage-mode") +def get_storage_mode( + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + mode = crud_setting.get_setting(db, "storage_mode") + return {"mode": mode or config.STORAGE_MODE} + +@router.put("/settings/storage-mode") +def update_storage_mode( + mode: str, + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + if mode not in ["gcs", "local"]: + raise HTTPException(status_code=400, detail="Invalid storage mode") + + crud_setting.update_setting(db, "storage_mode", mode) + return {"message": f"Storage mode updated to {mode}", "mode": mode} + +@router.get("/stats/performance") +def get_performance_stats( + metric: str, + days: int = 30, + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + end_date = datetime.utcnow() + start_date = end_date - timedelta(days=days) + + if metric == "users": + query = db.query( + func.date(User.created_at).label("date"), + func.count(User.id).label("value") + ).filter(User.created_at >= start_date) + elif metric == "videos": + query = db.query( + func.date(Video.created_at).label("date"), + func.count(Video.id).label("value") + ).filter(Video.created_at >= start_date) + elif metric == "premium": + query = db.query( + func.date(User.created_at).label("date"), + func.count(User.id).label("value") + ).filter(User.created_at >= start_date, User.is_premium == True) + elif metric == "views": + query = db.query( + func.date(View.created_at).label("date"), + func.count(View.id).label("value") + ).filter(View.created_at >= start_date) + elif metric == "revenue": + query = db.query( + func.date(Transaction.created_at).label("date"), + func.sum(Transaction.amount).label("value") + ).filter( + Transaction.created_at >= start_date, + Transaction.transaction_type == 'pro_subscription' + ) + else: + raise HTTPException(status_code=400, detail="Invalid metric") + + results = query.group_by("date").order_by("date").all() + + return [{"date": str(r.date), "value": float(r.value or 0)} for r in results] + +@router.get("/config") +def get_admin_config( + current_user: dict = Depends(admin_only) +): + return { + "rust_service_url": config.RUST_SERVICE_URL + } + +# Challenges Management + +@router.get("/challenges", response_model=List[schemas.Challenge]) +def read_challenges( + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + return db.query(Challenge).order_by(Challenge.created_at.desc()).all() + +@router.post("/challenges", response_model=schemas.Challenge) +def create_challenge( + challenge_in: schemas.ChallengeCreate, + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + db_challenge = Challenge(**challenge_in.model_dump()) + db.add(db_challenge) + db.commit() + db.refresh(db_challenge) + + # Dispatch Celery background task for email broadcasting + queue_new_challenge_announcement.delay(db_challenge.id) + + return db_challenge + +@router.put("/challenges/{challenge_id}", response_model=schemas.Challenge) +def update_challenge( + challenge_id: int, + challenge_in: schemas.ChallengeBase, # using base for partial update logic if desired or complete update + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + db_challenge = db.query(Challenge).filter(Challenge.id == challenge_id).first() + if not db_challenge: + raise HTTPException(status_code=404, detail="Challenge not found") + + update_data = challenge_in.model_dump(exclude_unset=True) + for key, value in update_data.items(): + setattr(db_challenge, key, value) + + db.commit() + db.refresh(db_challenge) + return db_challenge + +@router.delete("/challenges/{challenge_id}") +def delete_challenge( + challenge_id: int, + db: Session = Depends(get_db), + current_user: dict = Depends(admin_only) +): + db_challenge = db.query(Challenge).filter(Challenge.id == challenge_id).first() + if not db_challenge: + raise HTTPException(status_code=404, detail="Challenge not found") + + db.delete(db_challenge) + db.commit() + return {"message": "Challenge deleted successfully"} + + +# Content Reports Admin APIs +from app.schemas.report import ReportResponse, ReportAction, AuditLogResponse +from app.models.models import ContentReport, ModerationAuditLog, Comment, Post + +@router.get("/reports", response_model=List[ReportResponse]) +def get_reports( + status: Optional[str] = None, + content_type: Optional[str] = None, + skip: int = 0, + limit: int = 100, + db: Session = Depends(get_db), + current_user = Depends(admin_only) +): + query = db.query(ContentReport) + if status: + query = query.filter(ContentReport.status == status) + if content_type: + query = query.filter(ContentReport.content_type == content_type) + + reports = query.order_by(ContentReport.created_at.desc()).offset(skip).limit(limit).all() + + response_list = [] + for r in reports: + reporter_username = r.reporter.username if r.reporter else "Unknown" + resolver_username = r.resolver.username if r.resolver else None + + preview = "Content unavailable" + creator = "Unknown" + c_id = r.video_id or r.post_id or r.comment_id or 0 + + if r.content_type in ["video", "flash"] and r.video: + preview = r.video.title + creator = r.video.owner.username if r.video.owner else "Unknown" + c_id = r.video.public_id if r.video.public_id else str(r.video.id) + elif r.content_type == "post" and r.post: + preview = r.post.content[:100] + "..." if len(r.post.content) > 100 else r.post.content + creator = r.post.owner.username if r.post.owner else "Unknown" + c_id = r.post.id + elif r.content_type == "comment" and r.comment: + preview = r.comment.content[:100] + "..." if len(r.comment.content) > 100 else r.comment.content + creator = r.comment.owner.username if r.comment.owner else "Unknown" + c_id = r.comment.id + + response_list.append( + ReportResponse( + id=r.id, + reporter_id=r.reporter_id, + reporter_username=reporter_username, + content_type=r.content_type, + content_id=c_id, + reason=r.reason, + description=r.description, + status=r.status, + created_at=r.created_at, + resolved_at=r.resolved_at, + resolved_by=r.resolved_by, + resolver_username=resolver_username, + notes=r.notes, + reported_content_preview=preview, + reported_content_creator=creator + ) + ) + return response_list + +@router.post("/reports/{report_id}/action") +def take_report_action( + report_id: int, + action_in: ReportAction, + db: Session = Depends(get_db), + current_user = Depends(admin_only) +): + report = db.query(ContentReport).filter(ContentReport.id == report_id).first() + if not report: + raise HTTPException(status_code=404, detail="Report not found") + + action = action_in.action.lower() + notes = action_in.notes + + # Identify content creator + creator_user = None + target_id_str = "" + + if report.content_type in ["video", "flash"] and report.video: + creator_user = report.video.owner + target_id_str = report.video.public_id or str(report.video.id) + elif report.content_type == "post" and report.post: + creator_user = report.post.owner + target_id_str = str(report.post.id) + elif report.content_type == "comment" and report.comment: + creator_user = report.comment.owner + target_id_str = str(report.comment.id) + + # 1. Update Report status + report.status = "dismissed" if action == "dismiss" else "resolved" + report.resolved_at = datetime.utcnow() + report.resolved_by = current_user.id + report.notes = notes + + # 2. Perform requested Action + details_str = f"Action taken: {action} by admin: {current_user.username}. Notes: {notes}" + + if action == "delete_content": + if report.content_type in ["video", "flash"] and report.video: + db.delete(report.video) + elif report.content_type == "post" and report.post: + db.delete(report.post) + elif report.content_type == "comment" and report.comment: + db.delete(report.comment) + + elif action == "suspend_user": + if creator_user: + creator_user.is_active = False + details_str += f" | Suspended user: @{creator_user.username}" + + # 3. Create Audit Log + audit_log = ModerationAuditLog( + action=f"report_{action}", + moderator_id=current_user.id, + target_type=report.content_type, + target_id=target_id_str, + details=details_str + ) + db.add(audit_log) + db.commit() + + return {"message": f"Action '{action}' processed successfully."} + +@router.get("/moderation/audit-logs", response_model=List[AuditLogResponse]) +def get_moderation_audit_logs( + skip: int = 0, + limit: int = 100, + db: Session = Depends(get_db), + current_user = Depends(admin_only) +): + logs = db.query(ModerationAuditLog).order_by(ModerationAuditLog.created_at.desc()).offset(skip).limit(limit).all() + + response_list = [] + for l in logs: + mod_name = l.moderator.username if l.moderator else "System" + response_list.append( + AuditLogResponse( + id=l.id, + action=l.action, + moderator_id=l.moderator_id, + moderator_username=mod_name, + target_type=l.target_type, + target_id=l.target_id, + details=l.details, + created_at=l.created_at + ) + ) + return response_list + diff --git a/app/api/v1/endpoints/ads.py b/app/api/v1/endpoints/ads.py new file mode 100644 index 0000000000000000000000000000000000000000..f85594f18915ec383d3ef798dfd3f0d6b46d50ca --- /dev/null +++ b/app/api/v1/endpoints/ads.py @@ -0,0 +1,12 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from typing import List +from app.db.session import get_db +from app.schemas import schemas + +router = APIRouter() + +@router.get("", response_model=List[schemas.Ad]) +def get_active_ads(db: Session = Depends(get_db)): + from app.models.models import SponsoredAd + return db.query(SponsoredAd).filter(SponsoredAd.is_active == True).all() diff --git a/app/api/v1/endpoints/auth.py b/app/api/v1/endpoints/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf2ea174bc118c5003da9c8b24ed27bc72dc4f5 --- /dev/null +++ b/app/api/v1/endpoints/auth.py @@ -0,0 +1,328 @@ +from datetime import timedelta +from fastapi import APIRouter, Depends, HTTPException, status, Request +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.orm import Session +from google.oauth2 import id_token +from google.auth.transport import requests + +from app.db.session import get_db +from app.core import security, config +from app.crud import user as crud_user +from app.schemas import schemas +from app.models.models import User, UserSession +from app.services.email_service import send_verification_email +import hashlib +import logging + +logger = logging.getLogger(__name__) + +router = APIRouter() + +@router.post("/token", response_model=schemas.Token) +async def login_for_access_token( + request: Request, + db: Session = Depends(get_db), + form_data: OAuth2PasswordRequestForm = Depends() +): + # Rate Limit: 10 attempts per minute per IP + if not security.check_rate_limit(f"ratelimit:login:{request.client.host}", 10, 60): + raise HTTPException(status_code=429, detail="Too many login attempts. Please wait.") + + # Support login by username OR email + user = crud_user.get_user_by_username(db, username=form_data.username) + if not user: + user = crud_user.get_user_by_email(db, email=form_data.username) + + if not user or not security.verify_password(form_data.password, user.hashed_password): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + + + if getattr(user, 'two_factor_enabled', False) is True: + methods = ["totp"] + if user.recovery_codes: + methods.append("recovery_code") + return {"two_factor_required": True, "username": user.username, "methods": methods} + + access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = security.create_access_token( + data={"sub": user.username}, expires_delta=access_token_expires + ) + + # Create Session + token_hash = hashlib.sha256(access_token.encode()).hexdigest() + new_session = UserSession( + user_id=user.id, + token_hash=token_hash, + device_info="Mock Device (Browser)", + ip_address="127.0.0.1" + ) + db.add(new_session) + db.commit() + + return {"access_token": access_token, "token_type": "bearer", "username": user.username} + +@router.post("/register", response_model=schemas.VerificationResponse) +def register_user(request: Request, user_in: schemas.UserCreate, db: Session = Depends(get_db)): + # Rate Limit: 3 registrations per hour per IP (very strict) + if not security.check_rate_limit(f"ratelimit:register:{request.client.host}", 3, 3600): + raise HTTPException(status_code=429, detail="Too many registration attempts. Please wait.") + + db_user = crud_user.get_user_by_email(db, email=user_in.email) + if db_user: + raise HTTPException(status_code=400, detail="Email already registered") + + db_user = crud_user.get_user_by_username(db, username=user_in.username) + if db_user: + raise HTTPException(status_code=400, detail="Username already taken") + + user = crud_user.create_user(db, user=user_in, is_onboarded=True, ip_address=request.client.host) + user.is_verified = False # Mandatory verification + db.commit() + + # Generate and send verification code + code = crud_user.create_verification_code(db, email=user.email) + try: + send_verification_email(user.email, code) + except Exception as e: + logger.error(f"[auth] Verification email failed for {user.email}: {e}") + # We don't fail registration if email sending fails in dev, but in prod we might + + db.refresh(user) + + return { + "message": "Registration successful. Welcome to Monteeq!", + "email": user.email, + "username": user.username + } + +@router.post("/verify-email", response_model=schemas.VerificationResponse) +def verify_email(data: schemas.EmailVerification, db: Session = Depends(get_db)): + if crud_user.verify_code(db, email=data.email, code=data.code): + user = crud_user.get_user_by_email(db, email=data.email) + if user: + # Update is_verified + user.is_verified = True + db.commit() + db.refresh(user) + return {"message": "Email verified successfully", "username": user.username} + + raise HTTPException(status_code=400, detail="Invalid or expired verification code") + +@router.post("/resend-verification", response_model=schemas.VerificationResponse) +def resend_verification(data: schemas.ResendVerification, db: Session = Depends(get_db)): + """Resend the email verification code. Rate-limited by code expiry.""" + user = crud_user.get_user_by_email(db, email=data.email) + if not user: + raise HTTPException(status_code=404, detail="Email not registered") + + if user.is_verified: + raise HTTPException(status_code=400, detail="Email is already verified.") + + code = crud_user.create_verification_code(db, email=data.email) + send_verification_email(data.email, code) + + return { + "message": "A new verification code has been sent to your email.", + "email": data.email, + "username": user.username + } + +@router.post("/google", response_model=schemas.Token) +async def google_auth(request: Request, auth_data: schemas.UserGoogleAuth, db: Session = Depends(get_db)): + try: + idinfo = id_token.verify_oauth2_token( + auth_data.credential, requests.Request(), config.GOOGLE_CLIENT_ID + ) + email = idinfo['email'] + google_id = idinfo['sub'] + name = idinfo.get('name', email.split('@')[0]) + picture = idinfo.get('picture') + + user = crud_user.get_user_by_email(db, email=email) + if not user: + # Generate a temporary unique username + base_username = name.lower().replace(" ", "") + if not base_username: + base_username = "user" + username = base_username + suffix = 1 + while crud_user.get_user_by_username(db, username=username): + username = f"{base_username}{suffix}" + suffix += 1 + + user_create = schemas.UserCreate( + username=username, + email=email, + full_name=name, + profile_pic=picture, + password=None # Google auth users don't have passwords + ) + # Google users are auto-verified + user = crud_user.create_user(db, user=user_create, google_id=google_id, is_onboarded=False, ip_address=request.client.host) + user.is_verified = True + db.commit() + db.refresh(user) + else: + # If user exists but is trying to 'sign up' with Google, we might want to distinguish. + # But the requirement is: "if the email was registered, tell him to login" + # If they are using the Google auth flow, they ARE logging in. + # However, if they don't have a google_id, they originally signed up with a password. + if not user.google_id: + # This matches "tell him to login" (using his password) + raise HTTPException( + status_code=400, + detail="Email already registered with password. Please log in with your credentials." + ) + + if picture and not user.profile_pic: + user.profile_pic = picture + + user.is_verified = True + db.commit() + db.refresh(user) + + if getattr(user, 'two_factor_enabled', False) is True: + methods = ["totp"] + if user.recovery_codes: + methods.append("recovery_code") + return {"two_factor_required": True, "username": user.username, "methods": methods} + + access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = security.create_access_token( + data={"sub": user.username}, expires_delta=access_token_expires + ) + + # Create Session + token_hash = hashlib.sha256(access_token.encode()).hexdigest() + new_session = UserSession( + user_id=user.id, + token_hash=token_hash, + device_info="Google Auth Device", + ip_address="127.0.0.1" + ) + db.add(new_session) + db.commit() + + return {"access_token": access_token, "token_type": "bearer", "username": user.username} + + except ValueError as e: + print(f"Google Auth Error: {str(e)}") + raise HTTPException(status_code=400, detail=f"Invalid Google token: {str(e)}") + +@router.post("/verify-2fa", response_model=schemas.Token) +def verify_login_2fa( + data: schemas.TokenData, # Reusing schemas to avoid new ones + db: Session = Depends(get_db) +): + """Verify TOTP code for login.""" + if not data.username or not data.code: + raise HTTPException(status_code=400, detail="Missing username or code") + + user = crud_user.get_user_by_username(db, username=data.username) + if not user or not user.totp_secret: + raise HTTPException(status_code=401, detail="Could not validate credentials") + + import pyotp + import json + + is_valid = False + + # Try TOTP + totp = pyotp.TOTP(user.totp_secret) + if totp.verify(data.code): + is_valid = True + + # Try Recovery Codes + if not is_valid and user.recovery_codes: + codes = json.loads(user.recovery_codes) + hashed_input = hashlib.sha256(data.code.replace("-", "").upper().encode()).hexdigest() + if hashed_input in codes: + is_valid = True + # Consume the code + codes.remove(hashed_input) + user.recovery_codes = json.dumps(codes) + db.commit() + + if not is_valid: + raise HTTPException(status_code=401, detail="Invalid verification code") + + access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = security.create_access_token( + data={"sub": user.username}, expires_delta=access_token_expires + ) + + # Create Session + token_hash = hashlib.sha256(access_token.encode()).hexdigest() + new_session = UserSession( + user_id=user.id, + token_hash=token_hash, + device_info="2FA Verified Device", + ip_address="127.0.0.1" + ) + db.add(new_session) + db.commit() + + return {"access_token": access_token, "token_type": "bearer", "username": user.username} + +@router.post("/forgot-password") +def forgot_password(data: schemas.ResendVerification, db: Session = Depends(get_db)): + """Send a secure reset link.""" + user = crud_user.get_user_by_email(db, email=data.email) + if not user: + raise HTTPException(status_code=404, detail="Email not found") + + import secrets + from datetime import datetime, timedelta + from app.models.models import VerificationCode + + token = secrets.token_urlsafe(32) + # Delete existing tokens for this email + db.query(VerificationCode).filter(VerificationCode.email == user.email).delete() + + # Store token in VerificationCode table (it's a String column) + # Reset links usually last longer than OTPs (e.g., 1 hour) + expires_at = datetime.now() + timedelta(hours=1) + db_code = VerificationCode(email=user.email, code=token, expires_at=expires_at) + db.add(db_code) + db.commit() + + try: + from app.services.email_service import send_password_reset_email + send_password_reset_email(user.email, token) + except Exception as e: + logger.error(f"[auth] Password reset email failed for {user.email}: {e}") + + return {"message": "A secure reset link has been sent to your email."} + +@router.post("/reset-password") +def reset_password(data: schemas.PasswordReset, db: Session = Depends(get_db)): + """Verify link token and update password.""" + # We reuse verify_code logic which checks code (token) and expiry + if crud_user.verify_code(db, email=data.email, code=data.code): + user = crud_user.get_user_by_email(db, email=data.email) + if user: + user.hashed_password = security.get_password_hash(data.new_password) + db.commit() + return {"message": "Password updated successfully. You can now log in."} + + raise HTTPException(status_code=400, detail="Invalid or expired reset link") + +@router.get("/check-username") +def check_username(username: str, db: Session = Depends(get_db)): + user = crud_user.get_user_by_username(db, username=username) + return {"available": user is None} + +@router.get("/check-email") +def check_email(email: str, db: Session = Depends(get_db)): + user = crud_user.get_user_by_email(db, email=email) + return {"available": user is None} + +@router.get("/check-email-exists") +def check_email_exists(email: str, db: Session = Depends(get_db)): + """Check if an email is registered.""" + user = crud_user.get_user_by_email(db, email=email) + return {"exists": user is not None} diff --git a/app/api/v1/endpoints/categories.py b/app/api/v1/endpoints/categories.py new file mode 100644 index 0000000000000000000000000000000000000000..bb7d7ab71b393489e8177808d66d947a07859ab1 --- /dev/null +++ b/app/api/v1/endpoints/categories.py @@ -0,0 +1,43 @@ +from typing import List + +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session + +from app.db.session import get_db +from app.schemas import schemas +from app.core.dependencies import get_current_user +from app.models.models import DiscoveredCategory, User +from app.services import category_service as cs + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.DiscoveredCategoryOut]) +def list_categories(db: Session = Depends(get_db)): + return cs.get_approved_categories(db) + + +@router.post("/discover") +def trigger_discovery( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): + if current_user.role != "admin": + raise HTTPException(status_code=403, detail="Admin access required") + + new_cats = cs.discover_categories(db) + return { + "message": f"Discovery complete. {len(new_cats)} new categories found.", + "new_categories": [c.name for c in new_cats], + } + + +@router.get("/{category_name}/videos", response_model=List[schemas.Video]) +def get_category_videos( + category_name: str, + video_type: str = "flash", + limit: int = 30, + db: Session = Depends(get_db), +): + videos = cs.get_videos_for_category(db, category_name, video_type, limit) + return videos diff --git a/app/api/v1/endpoints/challenges.py b/app/api/v1/endpoints/challenges.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1ffef444c04b1e8d0d68a6bf3a60862b0c6cea --- /dev/null +++ b/app/api/v1/endpoints/challenges.py @@ -0,0 +1,166 @@ +import os +import shutil +import tempfile +import logging +from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, BackgroundTasks +from sqlalchemy.orm import Session +from sqlalchemy import func +from typing import List, Optional + +from app.db.session import get_db +from app.schemas import schemas +from app.core.dependencies import get_current_user +from app.models.models import Challenge, ChallengeEntry, Video, User +from app.core.storage import storage +from app.crud import video as crud_video +from app.tasks.video_tasks import process_video_task +from app.services.challenge_service import resolve_expired_challenges + +logger = logging.getLogger(__name__) + +router = APIRouter() + +@router.get("/", response_model=List[schemas.Challenge]) +def list_challenges(db: Session = Depends(get_db)): + """List all challenges and automatically pick winners for expired once.""" + resolve_expired_challenges(db) + return db.query(Challenge).order_by(Challenge.created_at.desc()).all() + +@router.get("/{challenge_id}", response_model=schemas.Challenge) +def get_challenge(challenge_id: int, db: Session = Depends(get_db)): + """Get details for a specific challenge.""" + challenge = db.query(Challenge).filter(Challenge.id == challenge_id).first() + if not challenge: + raise HTTPException(status_code=404, detail="Challenge not found") + return challenge + +@router.post("/{challenge_id}/enter", response_model=schemas.ChallengeEntry) +async def enter_challenge( + challenge_id: int, + background_tasks: BackgroundTasks, + title: str = Form(...), + description: Optional[str] = Form(None), + file: UploadFile = File(...), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Participate in a challenge by uploading a new video.""" + challenge = db.query(Challenge).filter(Challenge.id == challenge_id).first() + if not challenge: + raise HTTPException(status_code=404, detail="Challenge not found") + + if not challenge.is_open: + raise HTTPException(status_code=400, detail="This challenge is closed for entries") + + if (challenge.is_paid or challenge.is_gold) and not current_user.is_premium: + raise HTTPException( + status_code=403, + detail=f"This is a { 'Gold' if challenge.is_gold else 'Paid' } Challenge. Upgrade to Monteeq Pro to enter!" + ) + + # Constraint: Free user can only enter ONE challenge total + if not current_user.is_premium: + total_entries = db.query(ChallengeEntry).filter(ChallengeEntry.user_id == current_user.id).count() + if total_entries >= 1: + raise HTTPException( + status_code=403, + detail="Free users are limited to 1 challenge entry total. Upgrade to Premium for unlimited entries!" + ) + + # Check if already entered THIS specific challenge (paranoid check, though above covers it for free users) + existing_entry = db.query(ChallengeEntry).filter( + ChallengeEntry.challenge_id == challenge_id, + ChallengeEntry.user_id == current_user.id + ).first() + + if existing_entry: + raise HTTPException(status_code=400, detail="You have already entered this challenge") + + # Handle Video Upload + import uuid + task_id = str(uuid.uuid4()) + source_key = f"raw/{task_id}_{file.filename}" + + try: + # Upload to storage (S3/GCS/Local) + storage.upload_file_obj(file.file, source_key) + except Exception as e: + logger.error(f"Failed to upload challenge video to storage: {e}") + raise HTTPException(status_code=500, detail="Failed to upload video to storage") + + # Initial DB record for Video + video_create_data = schemas.VideoCreate( + title=title, + description=description, + tags=f"challenge,challenge_{challenge_id}", + video_type="home", # Challenges use home-style videos + video_url="", + thumbnail_url="https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=60", + processing_key=task_id + ) + + # Update quota if applicable + if current_user.home_uploads is not None: + current_user.home_uploads += 1 + + db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id) + + # Create Challenge Entry + db_entry = ChallengeEntry( + challenge_id=challenge_id, + user_id=current_user.id, + video_id=db_video.id + ) + db.add(db_entry) + + # Increment challenge entry count + challenge.entry_count += 1 + + db.commit() + db.refresh(db_entry) + + # Start background processing + process_video_task.delay( + source_key, + "home", + title, + db_video.id, + False, # No custom thumbnail provided + task_id + ) + + return db_entry + +@router.get("/{challenge_id}/entry", response_model=Optional[schemas.ChallengeEntry]) +def check_entry( + challenge_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Check if the current user has entered a specific challenge.""" + return db.query(ChallengeEntry).filter( + ChallengeEntry.challenge_id == challenge_id, + ChallengeEntry.user_id == current_user.id + ).first() + +@router.get("/{challenge_id}/leaderboard", response_model=List[schemas.ChallengeLeaderboardEntry]) +def get_leaderboard(challenge_id: int, db: Session = Depends(get_db)): + """Fetch top performers for a challenge based on video views.""" + entries = db.query(ChallengeEntry).filter(ChallengeEntry.challenge_id == challenge_id).all() + + leaderboard = [] + for entry in entries: + video = entry.video + if not video: + continue + user = entry.user + leaderboard.append({ + "username": user.username, + "profile_pic": user.profile_pic, + "entry": entry, + "score": video.views # Requirement: Rank by performance (views) + }) + + # Sort by score descending + leaderboard.sort(key=lambda x: x["score"], reverse=True) + return leaderboard[:20] # Top 20 diff --git a/app/api/v1/endpoints/chat.py b/app/api/v1/endpoints/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..df3246a24345e4bf789d5f2dd0ac7de1c592128a --- /dev/null +++ b/app/api/v1/endpoints/chat.py @@ -0,0 +1,355 @@ +from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File +from sqlalchemy.orm import Session +from sqlalchemy import or_ +from typing import List +import os +import uuid +from app.core import config + +from app.db.session import get_db +from app.schemas import schemas +from app.core.dependencies import get_current_user +from app.models.models import User, Conversation, ChatMessage, UserDevicePrekeyBundle, UserOneTimePrekey + +router = APIRouter() + +@router.post("/keys", response_model=schemas.User) +def upload_public_key( + key_in: schemas.KeyUpload, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + current_user.public_key = key_in.public_key + db.commit() + db.refresh(current_user) + return current_user + +@router.get("/keys/{username}") +def get_user_public_key( + username: str, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + user = db.query(User).filter(User.username == username).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + return {"public_key": user.public_key} + +from sqlalchemy.exc import IntegrityError + +@router.post("/keys/prekey-bundle", response_model=schemas.PrekeyBundleOut) +def upload_prekey_bundle( + bundle_in: schemas.PrekeyBundleUpload, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + # Check if bundle already exists for this user and device + bundle = db.query(UserDevicePrekeyBundle).filter( + UserDevicePrekeyBundle.user_id == current_user.id, + UserDevicePrekeyBundle.device_id == bundle_in.device_id + ).first() + + if not bundle: + bundle = UserDevicePrekeyBundle( + user_id=current_user.id, + device_id=bundle_in.device_id, + identity_key=bundle_in.identity_key, + signed_prekey=bundle_in.signed_prekey, + signed_prekey_signature=bundle_in.signature + ) + db.add(bundle) + else: + bundle.identity_key = bundle_in.identity_key + bundle.signed_prekey = bundle_in.signed_prekey + bundle.signed_prekey_signature = bundle_in.signature + + try: + db.commit() + except IntegrityError: + db.rollback() + bundle = db.query(UserDevicePrekeyBundle).filter( + UserDevicePrekeyBundle.user_id == current_user.id, + UserDevicePrekeyBundle.device_id == bundle_in.device_id + ).first() + if bundle: + bundle.identity_key = bundle_in.identity_key + bundle.signed_prekey = bundle_in.signed_prekey + bundle.signed_prekey_signature = bundle_in.signature + db.commit() + else: + raise HTTPException(status_code=500, detail="Database integrity error during bundle upload") + + db.refresh(bundle) + + # Store new one-time prekeys + for otkey in bundle_in.one_time_prekeys: + exists = db.query(UserOneTimePrekey).filter( + UserOneTimePrekey.user_id == current_user.id, + UserOneTimePrekey.device_id == bundle_in.device_id, + UserOneTimePrekey.key_value == otkey + ).first() + if not exists: + new_otk = UserOneTimePrekey( + user_id=current_user.id, + device_id=bundle_in.device_id, + key_value=otkey, + used=False + ) + db.add(new_otk) + + try: + db.commit() + except IntegrityError: + db.rollback() + + return schemas.PrekeyBundleOut( + user_id=bundle.user_id, + device_id=bundle.device_id, + identity_key=bundle.identity_key, + signed_prekey=bundle.signed_prekey, + signature=bundle.signed_prekey_signature, + one_time_prekey=None + ) + +@router.get("/keys/prekey-bundle/{username}", response_model=List[schemas.PrekeyBundleOut]) +def get_recipient_prekey_bundles( + username: str, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + recipient = db.query(User).filter(User.username == username).first() + if not recipient: + raise HTTPException(status_code=404, detail="User not found") + + bundles = db.query(UserDevicePrekeyBundle).filter(UserDevicePrekeyBundle.user_id == recipient.id).all() + + response_bundles = [] + for b in bundles: + # Get one unused one-time prekey + otk = db.query(UserOneTimePrekey).filter( + UserOneTimePrekey.user_id == recipient.id, + UserOneTimePrekey.device_id == b.device_id, + UserOneTimePrekey.used == False + ).first() + + otk_value = None + if otk: + otk_value = otk.key_value + otk.used = True + db.add(otk) + + response_bundles.append( + schemas.PrekeyBundleOut( + user_id=b.user_id, + device_id=b.device_id, + identity_key=b.identity_key, + signed_prekey=b.signed_prekey, + signature=b.signed_prekey_signature, + one_time_prekey=otk_value + ) + ) + + db.commit() + return response_bundles + +@router.post("/keys/one-time-prekeys") +def upload_one_time_prekeys( + keys_in: schemas.OneTimePrekeysUpload, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + for key in keys_in.keys: + otk = UserOneTimePrekey( + user_id=current_user.id, + device_id=keys_in.device_id, + key_value=key, + used=False + ) + db.add(otk) + + db.commit() + return {"status": "ok", "added": len(keys_in.keys)} + +@router.get("/keys/devices") +def list_user_devices( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """List all registered devices for the current user.""" + bundles = db.query(UserDevicePrekeyBundle).filter( + UserDevicePrekeyBundle.user_id == current_user.id + ).all() + return [ + { + "device_id": b.device_id, + "created_at": b.created_at.isoformat() if b.created_at else None + } + for b in bundles + ] + +@router.delete("/keys/devices/{device_id}") +def revoke_device( + device_id: str, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Revoke a device by deleting its prekey bundle and associated one-time prekeys.""" + bundle = db.query(UserDevicePrekeyBundle).filter( + UserDevicePrekeyBundle.user_id == current_user.id, + UserDevicePrekeyBundle.device_id == device_id + ).first() + if not bundle: + raise HTTPException(status_code=404, detail="Device not found") + + # Delete associated one-time prekeys + db.query(UserOneTimePrekey).filter( + UserOneTimePrekey.user_id == current_user.id, + UserOneTimePrekey.device_id == device_id + ).delete() + + db.delete(bundle) + db.commit() + return {"status": "ok", "device_id": device_id} + +@router.post("/messages", response_model=schemas.ChatMessage) +def send_message( + message_in: schemas.ChatMessageCreate, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + # Find recipient + recipient = db.query(User).filter(User.username == message_in.recipient_username).first() + if not recipient: + raise HTTPException(status_code=404, detail="Recipient not found") + + from sqlalchemy import and_ + # Find or create conversation + conv = db.query(Conversation).filter( + or_( + and_(Conversation.user1_id == current_user.id, Conversation.user2_id == recipient.id), + and_(Conversation.user1_id == recipient.id, Conversation.user2_id == current_user.id) + ) + ).first() + + if not conv: + conv = Conversation(user1_id=current_user.id, user2_id=recipient.id) + db.add(conv) + db.commit() + db.refresh(conv) + + # Create message + message = ChatMessage( + conversation_id=conv.id, + sender_id=current_user.id, + encrypted_content=message_in.encrypted_content, + iv=message_in.iv, + recipient_key=message_in.recipient_key, + sender_key=message_in.sender_key, + message_type=message_in.message_type, + attachment_url=message_in.attachment_url, + file_metadata=message_in.file_metadata + ) + db.add(message) + db.commit() + db.refresh(message) + + # Real-time WebSocket push to both parties + import asyncio + from app.core.ws_manager import manager as ws_manager + ws_payload = { + "type": "new_message", + "message": { + "id": message.id, + "conversation_id": message.conversation_id, + "sender_id": message.sender_id, + "encrypted_content": message.encrypted_content, + "iv": message.iv, + "recipient_key": message.recipient_key, + "sender_key": message.sender_key, + "message_type": message.message_type, + "attachment_url": message.attachment_url, + "file_metadata": message.file_metadata, + "created_at": message.created_at.isoformat() + } + } + try: + loop = asyncio.get_event_loop() + loop.create_task(ws_manager.broadcast_to_conversation( + [current_user.id, recipient.id], ws_payload + )) + except Exception: + pass # WebSocket push is best-effort + + return message + +@router.get("/conversations", response_model=List[schemas.Conversation]) +def get_conversations( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + conversations = db.query(Conversation).filter( + or_(Conversation.user1_id == current_user.id, Conversation.user2_id == current_user.id) + ).all() + return conversations + +@router.get("/messages/{conversation_id}", response_model=List[schemas.ChatMessage]) +def get_messages( + conversation_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + # Check if user is part of the conversation + conv = db.query(Conversation).filter(Conversation.id == conversation_id).first() + if not conv: + raise HTTPException(status_code=404, detail="Conversation not found") + + if conv.user1_id != current_user.id and conv.user2_id != current_user.id: + raise HTTPException(status_code=403, detail="Not authorized to view these messages") + + messages = db.query(ChatMessage).filter(ChatMessage.conversation_id == conversation_id).order_by(ChatMessage.created_at.asc()).all() + return messages + +@router.post("/messages/ack") +def acknowledge_messages( + message_ids: List[int], + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + if not message_ids: + return {"status": "ok", "deleted": 0} + + # Find conversations the user belongs to + user_conv_ids = [ + r[0] for r in db.query(Conversation.id).filter( + (Conversation.user1_id == current_user.id) | (Conversation.user2_id == current_user.id) + ).all() + ] + + # Perform bulk delete on matching messages, bypassing session state sync warnings + deleted_count = db.query(ChatMessage).filter( + ChatMessage.id.in_(message_ids), + ChatMessage.conversation_id.in_(user_conv_ids) + ).delete(synchronize_session=False) + + db.commit() + return {"status": "ok", "deleted": deleted_count} + +@router.post("/upload", response_model=schemas.AttachmentResponse) +def upload_attachment( + file: UploadFile = File(...), + current_user: User = Depends(get_current_user) +): + # Ensure directory exists + attachments_dir = os.path.join(config.STATIC_DIR, "chat_attachments") + os.makedirs(attachments_dir, exist_ok=True) + + # Save file + file_id = str(uuid.uuid4()) + filename = f"{file_id}_{file.filename}" + file_path = os.path.join(attachments_dir, filename) + + with open(file_path, "wb") as f: + f.write(file.file.read()) + + url = f"{config.BASE_URL}/static/chat_attachments/{filename}" + return {"url": url, "filename": file.filename} diff --git a/app/api/v1/endpoints/comments.py b/app/api/v1/endpoints/comments.py new file mode 100644 index 0000000000000000000000000000000000000000..788fefe46cfe9030f388c34179241be97df2d561 --- /dev/null +++ b/app/api/v1/endpoints/comments.py @@ -0,0 +1,28 @@ +from typing import List, Optional +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app.db.session import get_db +from app.crud import video as crud_video +from app.schemas import schemas +from app.core.dependencies import get_current_user +from app.models import models + +from sqlalchemy import func +from app.models.models import Like + +router = APIRouter() + +@router.post("/{comment_id}/like") +def like_comment( + comment_id: int, + db: Session = Depends(get_db), + current_user: models.User = Depends(get_current_user) +): + liked = crud_video.toggle_like(db, user_id=current_user.id, comment_id=comment_id) + if liked: + crud_video.handle_like_side_effects(db, user_id=current_user.id, comment_id=comment_id) + + # Get updated like count + likes_count = db.query(func.count(Like.id)).filter(Like.comment_id == comment_id).scalar() or 0 + + return {"liked": liked, "likes_count": likes_count} diff --git a/app/api/v1/endpoints/email.py b/app/api/v1/endpoints/email.py new file mode 100644 index 0000000000000000000000000000000000000000..2c3e838794c6af92bd4c5be58a4ed4ba8c9c0c7e --- /dev/null +++ b/app/api/v1/endpoints/email.py @@ -0,0 +1,269 @@ +""" +Email preference and unsubscribe endpoints. + +GET /api/v1/email/unsubscribe?token= — one-click unsubscribe (from email link) +POST /api/v1/email/unsubscribe — programmatic unsubscribe (authenticated) +GET /api/v1/email/preferences — get current preferences (authenticated) +PATCH /api/v1/email/preferences — update preferences (authenticated) +POST /api/v1/email/webhook — ESP open/click webhook (internal) +""" + +import logging +from datetime import datetime, timezone +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException, Query, Request +from fastapi.responses import HTMLResponse +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.db.session import get_db +from app.models.models import User, EmailLog +from app.utils.unsubscribe_token import verify_unsubscribe_token +from app.core.dependencies import get_current_user + +logger = logging.getLogger(__name__) +router = APIRouter() + + +# ── Schemas ─────────────────────────────────────────────────────────────────── + +class EmailPreferencesUpdate(BaseModel): + email_weekly: Optional[bool] = None + email_challenges: Optional[bool] = None + email_payouts: Optional[bool] = None + email_marketing: Optional[bool] = None + + +class EmailPreferencesOut(BaseModel): + email_weekly: bool + email_challenges: bool + email_payouts: bool + email_marketing: bool + + class Config: + from_attributes = True + + +class WebhookPayload(BaseModel): + type: str # "email.opened" | "email.clicked" | "email.bounced" + message_id: str + timestamp: Optional[str] = None + + +# ── Unsubscribe (one-click, from email link) ────────────────────────────────── + +@router.get("/unsubscribe", response_class=HTMLResponse) +def one_click_unsubscribe( + token: str = Query(..., description="Signed unsubscribe token from email link"), + db: Session = Depends(get_db), +): + """ + One-click unsubscribe endpoint — linked from every marketing email footer. + Verifies the HMAC token and updates the relevant preference column. + Returns a friendly HTML confirmation page (no login required). + """ + result = verify_unsubscribe_token(token) + if not result: + raise HTTPException(status_code=400, detail="Invalid or expired unsubscribe link.") + + user_id, group = result + user = db.query(User).filter(User.id == user_id).first() + if not user: + raise HTTPException(status_code=404, detail="Account not found.") + + _apply_unsubscribe(user, group, db) + + return HTMLResponse(content=_unsubscribe_page(user.username, group), status_code=200) + + +@router.post("/unsubscribe") +def api_unsubscribe( + group: str = Query(default="marketing"), + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db), +): + """Programmatic unsubscribe for authenticated users via settings page.""" + _apply_unsubscribe(current_user, group, db) + return {"status": "unsubscribed", "group": group} + + +def _apply_unsubscribe(user: User, group: str, db: Session): + mapping = { + "marketing": "email_marketing", + "weekly": "email_weekly", + "challenges": "email_challenges", + "all": None, # handled specially + } + if group == "all": + user.email_marketing = False + user.email_weekly = False + user.email_challenges = False + elif group in mapping: + setattr(user, mapping[group], False) + db.commit() + logger.info("User %s unsubscribed from group '%s'", user.id, group) + + +# ── Preferences (authenticated) ─────────────────────────────────────────────── + +@router.get("/preferences", response_model=EmailPreferencesOut) +def get_preferences(current_user: User = Depends(get_current_user)): + return current_user + + +@router.patch("/preferences", response_model=EmailPreferencesOut) +def update_preferences( + payload: EmailPreferencesUpdate, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db), +): + for field, value in payload.model_dump(exclude_none=True).items(): + setattr(current_user, field, value) + db.commit() + db.refresh(current_user) + return current_user + + +# ── Analytics (Admin only) ────────────────────────────────────────────────── + +@router.get("/analytics") +def get_email_analytics( + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db), +): + """ + Get aggregated email metrics per template type. + Includes send count, open count, open rate, click count, click-through rate. + """ + if current_user.role != "admin": + raise HTTPException(status_code=403, detail="Forbidden: Admin access required.") + + from sqlalchemy import func as sqlfunc + + # Query total sent, opened, clicked per template + stats = db.query( + EmailLog.template, + sqlfunc.count(EmailLog.id).label("sent"), + sqlfunc.count(EmailLog.opened_at).label("opened"), + sqlfunc.count(EmailLog.clicked_at).label("clicked"), + sqlfunc.count(sqlfunc.nullif(EmailLog.bounced, False)).label("bounced") + ).group_by(EmailLog.template).all() + + results = [] + for row in stats: + sent = row.sent + opened = row.opened + clicked = row.clicked + open_rate = round((opened / sent) * 100, 2) if sent > 0 else 0.0 + ctr = round((clicked / sent) * 100, 2) if sent > 0 else 0.0 + results.append({ + "template": row.template, + "sent": sent, + "opened": opened, + "clicked": clicked, + "bounced": row.bounced, + "open_rate": open_rate, + "ctr": ctr + }) + + return {"templates": results} + + + +# ── ESP Webhook (open / click tracking) ────────────────────────────────────── + +@router.post("/webhook") +async def esp_webhook(request: Request, db: Session = Depends(get_db)): + """ + Receives open/click/bounce events from ESP (Resend or Zoho). + Updates email_log rows for analytics. + + Protect this endpoint with an API secret in production: + verify request headers against WEBHOOK_SECRET env var. + """ + try: + body = await request.json() + event_type = body.get("type", "") + message_id = body.get("data", {}).get("email_id") or body.get("message_id", "") + + if not message_id: + return {"status": "ignored"} + + log_row = db.query(EmailLog).filter( + EmailLog.esp_message_id == message_id + ).first() + + if not log_row: + return {"status": "not_found"} + + now = datetime.now(timezone.utc) + if event_type in ("email.opened", "opened") and not log_row.opened_at: + log_row.opened_at = now + elif event_type in ("email.clicked", "clicked") and not log_row.clicked_at: + log_row.clicked_at = now + elif event_type in ("email.bounced", "bounced"): + log_row.bounced = True + elif event_type in ("email.complained", "complained"): + log_row.unsubscribed = True + + db.commit() + return {"status": "ok"} + + except Exception as e: + logger.error("ESP webhook error: %s", e) + return {"status": "error"} + + +# ── Unsubscribe confirmation page ───────────────────────────────────────────── + +def _unsubscribe_page(username: str, group: str) -> str: + group_label = { + "marketing": "marketing and promotional emails", + "weekly": "the weekly digest", + "challenges": "challenge announcement emails", + "all": "all non-essential emails", + }.get(group, "these emails") + + return f""" + + + + + Unsubscribed — Monteeq + + + +
+

You're unsubscribed, {username}.

+

We've removed you from {group_label}. You won't receive them anymore.

+ Back to Monteeq +

+ You'll still receive account security emails and important service notifications. + You can update your preferences anytime in + Settings. +

+
+ +""" diff --git a/app/api/v1/endpoints/following.py b/app/api/v1/endpoints/following.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f6b77944302badf87fa2370e08278197a8cf96 --- /dev/null +++ b/app/api/v1/endpoints/following.py @@ -0,0 +1,113 @@ +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy.orm import Session, joinedload +from sqlalchemy import desc, func, or_ +from typing import List, Optional, Any +from datetime import datetime + +from app.db.session import get_db +from app.core.dependencies import get_current_user +from app.models.models import Follow, Video, Post, User +from app.schemas import schemas + +router = APIRouter() + +@router.get("/feed", response_model=List[schemas.FollowingFeedItem]) +async def get_following_feed( + skip: int = 0, + limit: int = 20, + content_type: Optional[str] = Query(None, pattern="^(all|videos|flash|posts)$"), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Returns a mixed personalized feed containing videos, flash videos, and community posts + ONLY from creators the current user follows. + """ + # 1. Get followed user IDs + followed_ids = db.query(Follow.following_id).filter(Follow.follower_id == current_user.id).all() + followed_ids = [r[0] for r in followed_ids] + + if not followed_ids: + return [] + + # 2. Fetch content with specific ratio: ~8 videos, ~2 flash, ~1 post per page (if limit is 20) + # We'll adjust based on the limit provided. + + items = [] + + # Calculate sub-limits + if content_type == "videos": + v_limit, f_limit, p_limit = limit, 0, 0 + elif content_type == "flash": + v_limit, f_limit, p_limit = 0, limit, 0 + elif content_type == "posts": + v_limit, f_limit, p_limit = 0, 0, limit + else: + # Default mix (all) + v_limit = int(limit * 0.7) # ~14 + f_limit = int(limit * 0.2) # ~4 + p_limit = limit - v_limit - f_limit # ~2 + + # Fetch Videos + if v_limit > 0: + videos = db.query(Video).options(joinedload(Video.owner)).filter( + Video.owner_id.in_(followed_ids), + Video.status == "approved", + Video.video_type == "home" + ).order_by(desc(Video.created_at)).offset(skip).limit(v_limit).all() + for v in videos: + items.append({"type": "video", "data": v, "created_at": v.created_at}) + + # Fetch Flash + if f_limit > 0: + flash = db.query(Video).options(joinedload(Video.owner)).filter( + Video.owner_id.in_(followed_ids), + Video.status == "approved", + Video.video_type == "flash" + ).order_by(desc(Video.created_at)).offset(skip).limit(f_limit).all() + for f in flash: + items.append({"type": "flash", "data": f, "created_at": f.created_at}) + + # Fetch Posts + if p_limit > 0: + posts = db.query(Post).options(joinedload(Post.owner)).filter( + Post.owner_id.in_(followed_ids), + Post.is_active == True + ).order_by(desc(Post.created_at)).offset(skip).limit(p_limit).all() + for p in posts: + items.append({"type": "post", "data": p, "created_at": p.created_at}) + + # 3. Interleave/Sort + # Sort by created_at desc to mix them naturally + items.sort(key=lambda x: x["created_at"], reverse=True) + + return items[:limit] + +@router.get("/recommendations", response_model=List[schemas.UserPublic]) +async def get_recommended_creators( + db: Session = Depends(get_db), + current_user: Optional[User] = Depends(get_current_user) +): + """ + Recommend creators based on follower count and activity. + Excludes creators the user is already following. + """ + # Exclude self and already followed + excluded_ids = [current_user.id] if current_user else [] + if current_user: + followed = db.query(Follow.following_id).filter(Follow.follower_id == current_user.id).all() + excluded_ids.extend([r[0] for r in followed]) + + # Recommended: Top 10 creators by follower count + # Since we don't have a followers_count column in User yet, we join with Follow + recommendations = ( + db.query(User, func.count(Follow.id).label("f_count")) + .outerjoin(Follow, Follow.following_id == User.id) + .filter(~User.id.in_(excluded_ids)) + .group_by(User.id) + .order_by(desc("f_count")) + .limit(10) + .all() + ) + + return [r[0] for r in recommendations] diff --git a/app/api/v1/endpoints/history.py b/app/api/v1/endpoints/history.py new file mode 100644 index 0000000000000000000000000000000000000000..7bbaa3099b45c3455c05f06de129b908a1b58aff --- /dev/null +++ b/app/api/v1/endpoints/history.py @@ -0,0 +1,152 @@ +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select +from sqlalchemy import func, delete, update +from sqlalchemy.orm import selectinload +from typing import Optional +from datetime import datetime, timedelta + +from app.db.async_session import get_async_db +from app.schemas import library as schemas +from app.models.library import WatchHistory +from app.models.models import Video +from app.core.async_dependencies import get_async_current_user + +router = APIRouter() + +@router.get("/", response_model=schemas.HistoryResponse) +async def get_history( + page: int = 1, + limit: int = 20, + filter: Optional[str] = Query(None, pattern="^(today|this_week|this_month|all)$"), + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + offset = (page - 1) * limit + query = select(WatchHistory).options( + selectinload(WatchHistory.video).selectinload(Video.owner) + ).filter(WatchHistory.user_id == current_user.id) + + if filter == "today": + today = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) + query = query.filter(WatchHistory.watched_at >= today) + elif filter == "this_week": + week_ago = datetime.utcnow() - timedelta(days=7) + query = query.filter(WatchHistory.watched_at >= week_ago) + elif filter == "this_month": + month_ago = datetime.utcnow() - timedelta(days=30) + query = query.filter(WatchHistory.watched_at >= month_ago) + + # Total count + count_query = select(func.count()).select_from(query.subquery()) + total = await db.scalar(count_query) + + # Items + query = query.order_by(WatchHistory.watched_at.desc()).offset(offset).limit(limit) + result = await db.execute(query) + items = result.scalars().all() + + return { + "items": items, + "page": page, + "limit": limit, + "total": total, + "has_more": offset + limit < total + } + +@router.delete("/") +async def clear_history( + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + await db.execute(delete(WatchHistory).filter(WatchHistory.user_id == current_user.id)) + await db.commit() + return {"status": "success"} + +async def get_video_db_async(db: AsyncSession, video_id: str) -> Video: + if isinstance(video_id, str) and not video_id.isdigit(): + result = await db.execute(select(Video).filter(Video.public_id == video_id)) + else: + result = await db.execute(select(Video).filter(Video.id == int(video_id))) + video = result.scalar_one_or_none() + if not video: + raise HTTPException(status_code=404, detail="Video not found") + return video + +@router.delete("/{video_id}") +async def remove_from_history( + video_id: str, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + video = await get_video_db_async(db, video_id) + await db.execute(delete(WatchHistory).filter( + WatchHistory.user_id == current_user.id, + WatchHistory.video_id == video.id + )) + await db.commit() + return {"status": "success"} + +@router.post("/track") +async def track_history( + payload: schemas.HistoryTrackRequest, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + video = await get_video_db_async(db, str(payload.video_id)) + # UPSERT Logic + result = await db.execute(select(WatchHistory).filter( + WatchHistory.user_id == current_user.id, + WatchHistory.video_id == video.id + )) + history = result.scalar_one_or_none() + + if not history: + history = WatchHistory( + user_id=current_user.id, + video_id=video.id, + progress_seconds=payload.progress_seconds, + duration_seconds=payload.duration_seconds, + is_completed=payload.is_completed + ) + db.add(history) + else: + history.progress_seconds = payload.progress_seconds + history.duration_seconds = payload.duration_seconds + history.is_completed = payload.is_completed + history.watched_at = func.now() + + await db.commit() + return {"status": "success"} + +@router.patch("/{video_id}/progress") +async def update_progress( + video_id: str, + progress: schemas.HistoryProgressUpdate, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + video = await get_video_db_async(db, video_id) + result = await db.execute(select(WatchHistory).filter( + WatchHistory.user_id == current_user.id, + WatchHistory.video_id == video.id + )) + history = result.scalar_one_or_none() + + if not history: + history = WatchHistory( + user_id=current_user.id, + video_id=video.id, + progress_seconds=progress.progress_seconds, + duration_seconds=progress.duration_seconds or video.duration, + is_completed=progress.is_completed + ) + db.add(history) + else: + history.progress_seconds = progress.progress_seconds + history.duration_seconds = progress.duration_seconds or history.duration_seconds + history.is_completed = progress.is_completed + history.watched_at = func.now() + + await db.commit() + return {"status": "success"} diff --git a/app/api/v1/endpoints/library.py b/app/api/v1/endpoints/library.py new file mode 100644 index 0000000000000000000000000000000000000000..c8c6f26eb3107363985884b8c0c84c62bc047bdc --- /dev/null +++ b/app/api/v1/endpoints/library.py @@ -0,0 +1,27 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select +from sqlalchemy import func + +from app.db.async_session import get_async_db +from app.schemas import library as schemas +from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo +from app.core.async_dependencies import get_async_current_user + +router = APIRouter() + +@router.get("/stats", response_model=schemas.LibraryStats) +async def get_library_stats( + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + history_count = await db.scalar(select(func.count()).filter(WatchHistory.user_id == current_user.id)) + watch_later_count = await db.scalar(select(func.count()).filter(LibraryWatchLater.user_id == current_user.id)) + + liked_count = await db.scalar(select(func.count()).filter(LikedVideo.user_id == current_user.id)) + + return { + "history_count": history_count or 0, + "watch_later_count": watch_later_count or 0, + "liked_count": liked_count or 0 + } diff --git a/app/api/v1/endpoints/liked.py b/app/api/v1/endpoints/liked.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9e5f7ea5513691642f931c7df503a9c5e1404b --- /dev/null +++ b/app/api/v1/endpoints/liked.py @@ -0,0 +1,97 @@ +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select +from sqlalchemy import func, delete +from sqlalchemy.orm import selectinload +from typing import Optional + +from app.db.async_session import get_async_db +from app.schemas import library as schemas +from app.models.library import LikedVideo +from app.models.models import Video +from app.core.async_dependencies import get_async_current_user + +router = APIRouter() + +@router.get("/", response_model=schemas.LikedResponse) +async def get_liked_videos( + page: int = 1, + limit: int = 20, + category: Optional[str] = Query("all"), + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + offset = (page - 1) * limit + query = select(LikedVideo).options( + selectinload(LikedVideo.video).selectinload(Video.owner) + ).filter(LikedVideo.user_id == current_user.id) + + # Category filter (if Video model supports it) + if category != "all": + # This assumes existing Video model has a 'video_type' or similar field that matches category + # Or we could filter by tags. For now we follow the 'category' requirement. + query = query.join(Video).filter(Video.video_type == category) + + # Total + count_query = select(func.count()).select_from(query.subquery()) + total = await db.scalar(count_query) + + # Items + query = query.order_by(LikedVideo.liked_at.desc()).offset(offset).limit(limit) + result = await db.execute(query) + items = result.scalars().all() + + return { + "items": items, + "page": page, + "limit": limit, + "total": total, + "has_more": offset + limit < total + } + +async def get_video_db_async(db: AsyncSession, video_id: str) -> Video: + if isinstance(video_id, str) and not video_id.isdigit(): + result = await db.execute(select(Video).filter(Video.public_id == video_id)) + else: + result = await db.execute(select(Video).filter(Video.id == int(video_id))) + video = result.scalar_one_or_none() + if not video: + raise HTTPException(status_code=404, detail="Video not found") + return video + +@router.post("/{video_id}") +async def like_video( + video_id: str, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + video = await get_video_db_async(db, video_id) + result = await db.execute(select(LikedVideo).filter( + LikedVideo.user_id == current_user.id, + LikedVideo.video_id == video.id + )) + if result.scalar_one_or_none(): + return {"status": "already_liked"} + + new_like = LikedVideo(user_id=current_user.id, video_id=video.id) + db.add(new_like) + + # Increment like count on video (requires existing field) + # await db.execute(update(Video).where(Video.id == video.id).values(likes_count=Video.likes_count + 1)) + + await db.commit() + return {"status": "success"} + +@router.delete("/{video_id}") +async def unlike_video( + video_id: str, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + video = await get_video_db_async(db, video_id) + await db.execute(delete(LikedVideo).filter( + LikedVideo.user_id == current_user.id, + LikedVideo.video_id == video.id + )) + await db.commit() + return {"status": "success"} diff --git a/app/api/v1/endpoints/metrics.py b/app/api/v1/endpoints/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..f4b434a4fadc2952de0d17ce63894481d49f4ed9 --- /dev/null +++ b/app/api/v1/endpoints/metrics.py @@ -0,0 +1,31 @@ +from fastapi import APIRouter, Request, BackgroundTasks +from typing import List, Dict, Any +from pydantic import BaseModel +import logging + +router = APIRouter() +logger = logging.getLogger(__name__) + +class MetricEvent(BaseModel): + type: str + video_id: Any + timestamp: int + duration_ms: float = None + +class MetricsBatchRequest(BaseModel): + events: List[MetricEvent] + +@router.post("/batch") +async def batch_metrics(request: MetricsBatchRequest, background_tasks: BackgroundTasks): + """ + Receive a batch of metrics from the frontend. + For now, we just log them. In production, these should be flushed to + a specialized metrics store (e.g. ClickHouse, Prometheus, or Mixpanel). + """ + # background_tasks.add_task(process_metrics, request.events) + logger.info(f"Received {len(request.events)} metric events from client") + return {"status": "ok", "received": len(request.events)} + +async def process_metrics(events: List[MetricEvent]): + # Future implementation: sync to analytics DB + pass diff --git a/app/api/v1/endpoints/monetization.py b/app/api/v1/endpoints/monetization.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbb710d7e69111e232211ab5dd0658d882bbd2f --- /dev/null +++ b/app/api/v1/endpoints/monetization.py @@ -0,0 +1,1181 @@ +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.responses import RedirectResponse +from sqlalchemy.orm import Session +from typing import List +import datetime +import logging +import hashlib +import hmac +import json + +from app.db.session import get_db +from app.schemas import schemas +from app.core.dependencies import get_current_user +from app.models.models import User, Wallet, Transaction, PayoutRequest +from app.crud.monetization import get_or_create_wallet, process_tip +from app.core.config import PAYSTACK_SECRET_KEY, STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, BASE_URL, FRONTEND_URL +import httpx +import stripe + +logger = logging.getLogger(__name__) + +router = APIRouter() + +# ── Paystack integration URLs ────────────────────────────────────────────── +# These are computed once at startup so they are always consistent. +# Copy the values printed in startup logs and paste them into Paystack Dashboard. +# +# Webhook URL → Paystack Dashboard → Settings → API Keys & Webhooks → Webhook URL +# Callback URL → Paystack Dashboard → Settings → API Keys & Webhooks → Callback URL +# +WEBHOOK_URL = f"{BASE_URL}/api/v1/monetization/webhook/paystack" +CALLBACK_URL = f"{BASE_URL}/api/v1/monetization/payment/callback" + +import logging as _log +_log.getLogger(__name__).info( + f"\n" \ + f" ╔══════════════════════════════════════════════════════════╗\n" \ + f" ║ Paystack Integration URLs (paste in dashboard) ║\n" \ + f" ╠══════════════════════════════════════════════════════════╣\n" \ + f" ║ Webhook URL : {WEBHOOK_URL:<42} ║\n" \ + f" ║ Callback URL: {CALLBACK_URL:<42} ║\n" \ + f" ╚══════════════════════════════════════════════════════════╝" +) + +@router.get("/wallet", response_model=schemas.Wallet) +def get_creator_wallet( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Fetch the authenticated user's wallet and transaction history.""" + return get_or_create_wallet(db, current_user.id) + +@router.post("/tip/{user_id}", response_model=schemas.Transaction) +def send_tip( + user_id: int, + amount: float, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Send a direct tip to a creator.""" + if amount <= 0: + raise HTTPException(status_code=400, detail="Tip amount must be positive.") + creator = db.query(User).filter(User.id == user_id).first() + if not creator: + raise HTTPException(status_code=404, detail="Creator not found") + + if creator.id == current_user.id: + raise HTTPException(status_code=400, detail="You cannot tip yourself") + + result = process_tip(db, from_user_id=current_user.id, to_user_id=creator.id, amount=amount) + if not result: + raise HTTPException(status_code=400, detail="Insufficient wallet balance. Please top up your wallet.") + return result + +# ------------------------------------------------------------------ # +# PAYOUT REQUEST ENDPOINTS +# ------------------------------------------------------------------ # + +@router.post("/payout/request", response_model=schemas.PayoutRequestSchema) +def request_payout( + payload: schemas.PayoutRequestCreate, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Creator requests a payout from their wallet. + Minimum payout: ₦1,000. Funds stay frozen until admin marks as completed. + """ + wallet = get_or_create_wallet(db, current_user.id) + balance = float(wallet.balance) + + MIN_PAYOUT = 1000.0 + if payload.amount < MIN_PAYOUT: + raise HTTPException(status_code=400, detail=f"Minimum payout is ₦{MIN_PAYOUT:,.2f}") + if payload.amount > balance: + raise HTTPException(status_code=400, detail=f"Insufficient balance. Your balance is ₦{balance:,.2f}") + + # Block duplicate pending requests + existing_pending = db.query(PayoutRequest).filter( + PayoutRequest.user_id == current_user.id, + PayoutRequest.status == "pending" + ).first() + if existing_pending: + raise HTTPException(status_code=400, detail="You already have a pending payout request. Please wait for it to be processed.") + + payout = PayoutRequest( + user_id=current_user.id, + wallet_id=wallet.id, + amount=payload.amount, + bank_details=payload.bank_details, + status="pending" + ) + + # Deduct from wallet immediately (held in escrow until approved) + from decimal import Decimal + wallet.balance -= Decimal(str(payload.amount)) + + db.add(payout) + db.commit() + db.refresh(payout) + return payout + +@router.get("/payout/my-requests", response_model=List[schemas.PayoutRequestSchema]) +def get_my_payout_requests( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """List the authenticated user's payout history.""" + return db.query(PayoutRequest).filter( + PayoutRequest.user_id == current_user.id + ).order_by(PayoutRequest.requested_at.desc()).all() + +# ------------------------------------------------------------------ # +# ADMIN-ONLY PAYOUT MANAGEMENT +# ------------------------------------------------------------------ # + +def _require_admin(current_user: User): + if current_user.role != "admin": + raise HTTPException(status_code=403, detail="Admin access required") + +@router.get("/admin/payouts", response_model=List[schemas.PayoutRequestSchema]) +def admin_list_payouts( + status: str = None, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Admin: list all payout requests, optionally filtered by status.""" + _require_admin(current_user) + q = db.query(PayoutRequest) + if status: + q = q.filter(PayoutRequest.status == status) + return q.order_by(PayoutRequest.requested_at.desc()).all() + +@router.get("/admin/transactions") +def admin_list_transactions( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Admin: view all transactions including pending and failed.""" + _require_admin(current_user) + return db.query(Transaction).order_by(Transaction.created_at.desc()).all() + +@router.put("/admin/payouts/{payout_id}", response_model=schemas.PayoutRequestSchema) +def admin_update_payout( + payout_id: int, + status: str, + admin_note: str = None, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Admin: approve, reject, or mark a payout as completed.""" + _require_admin(current_user) + payout = db.query(PayoutRequest).filter(PayoutRequest.id == payout_id).first() + if not payout: + raise HTTPException(status_code=404, detail="Payout request not found") + + valid_statuses = {"pending", "processing", "completed", "rejected"} + if status not in valid_statuses: + raise HTTPException(status_code=400, detail=f"Status must be one of: {valid_statuses}") + + # If rejected, refund the escrowed amount back to wallet + if status == "rejected" and payout.status != "rejected": + wallet = db.query(Wallet).filter(Wallet.id == payout.wallet_id).first() + if wallet: + from decimal import Decimal + wallet.balance += Decimal(str(payout.amount)) + + payout.status = status + payout.admin_note = admin_note + payout.processed_at = datetime.datetime.now() + db.commit() + db.refresh(payout) + return payout + +def get_or_create_stripe_price(price_amount: float, is_yearly: bool) -> str: + """Helper to dynamically find or create a Price ID in Stripe for the subscription.""" + stripe.api_key = STRIPE_SECRET_KEY + price_cents = int(price_amount * 100) + interval = "year" if is_yearly else "month" + product_name = f"Monteeq Pro {'Yearly' if is_yearly else 'Monthly'}" + + try: + prices = stripe.Price.list(active=True, limit=100) + for p in prices.auto_paging_iter(): + if p.unit_amount == price_cents and p.recurring and p.recurring.interval == interval: + try: + prod = stripe.Product.retrieve(p.product) + if "Monteeq Pro" in prod.name: + return p.id + except Exception: + pass + except Exception as e: + logger.warning(f"Error listing Stripe prices: {str(e)}") + + try: + product = stripe.Product.create( + name=product_name, + description="Access to premium creator features including ad-free, 4K rendering, gold challenges.", + ) + price = stripe.Price.create( + unit_amount=price_cents, + currency="usd", + recurring={"interval": interval}, + product=product.id, + ) + return price.id + except Exception as e: + logger.error(f"Error creating Stripe product/price: {str(e)}") + raise e + +@router.get("/pro/pricing", response_model=schemas.ProPricingResponse) +def get_pro_pricing(): + """Returns the current pricing for Monteeq Pro.""" + return {"monthly_price": 4.99, "yearly_price": 53.89} + +@router.post("/subscriptions/create", response_model=schemas.SubscriptionCreateResponse) +def create_subscription( + payload: schemas.SubscriptionCreateRequest, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Creates or retrieves a Stripe Customer, creates a subscription, + and returns the client secret of the payment intent to complete verification on the frontend. + """ + if current_user.subscription_tier == "pro" and current_user.subscription_status == "active": + raise HTTPException(status_code=400, detail="You already have an active subscription") + + stripe.api_key = STRIPE_SECRET_KEY + + customer_id = current_user.stripe_customer_id + if not customer_id: + try: + customer = stripe.Customer.create( + email=payload.billing_email, + name=payload.full_name, + metadata={ + "user_id": str(current_user.id), + "billing_country": payload.billing_country, + "billing_zip": payload.billing_zip + } + ) + customer_id = customer.id + current_user.stripe_customer_id = customer_id + db.commit() + except Exception as e: + logger.error(f"Failed to create Stripe customer: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to configure customer profile: {str(e)}") + else: + try: + stripe.Customer.modify( + customer_id, + email=payload.billing_email, + name=payload.full_name, + metadata={ + "user_id": str(current_user.id), + "billing_country": payload.billing_country, + "billing_zip": payload.billing_zip + } + ) + except Exception as e: + logger.warning(f"Failed to update Stripe customer: {str(e)}") + + price_amount = 53.89 if payload.is_yearly else 4.99 + try: + price_id = get_or_create_stripe_price(price_amount, payload.is_yearly) + except Exception as e: + raise HTTPException(status_code=500, detail=f"Failed to retrieve subscription plan price: {str(e)}") + + try: + if current_user.subscription_id: + try: + existing_sub = stripe.Subscription.retrieve(current_user.subscription_id) + if existing_sub.status in ["incomplete", "incomplete_expired"]: + stripe.Subscription.cancel(current_user.subscription_id) + except Exception: + pass + + # Support both new Basil API version (2025-03-31+) and legacy versions dynamically + try: + subscription = stripe.Subscription.create( + customer=customer_id, + items=[{"price": price_id}], + payment_behavior="default_incomplete", + payment_settings={"save_default_payment_method": "on_subscription"}, + expand=["latest_invoice.confirmation_secret"], + metadata={ + "user_id": str(current_user.id), + "payment_type": "pro_subscription", + "is_yearly": str(payload.is_yearly) + } + ) + client_secret = subscription.latest_invoice.confirmation_secret.client_secret + except Exception as e: + # If the Stripe API version is legacy, confirmation_secret expansion will fail. + # We then fall back to the legacy payment_intent expansion. + if "confirmation_secret" in str(e) or "Invalid expand" in str(e) or "attribute" in str(e): + logger.info("Falling back to legacy Stripe payment_intent expansion...") + subscription = stripe.Subscription.create( + customer=customer_id, + items=[{"price": price_id}], + payment_behavior="default_incomplete", + payment_settings={"save_default_payment_method": "on_subscription"}, + expand=["latest_invoice.payment_intent"], + metadata={ + "user_id": str(current_user.id), + "payment_type": "pro_subscription", + "is_yearly": str(payload.is_yearly) + } + ) + client_secret = subscription.latest_invoice.payment_intent.client_secret + else: + raise e + + subscription_id = subscription.id + + current_user.subscription_id = subscription_id + current_user.subscription_status = "incomplete" + current_user.subscription_tier = "pro" + db.commit() + + except Exception as e: + logger.error(f"Failed to create Stripe subscription: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to initialize subscription: {str(e)}") + + return { + "status": "success", + "subscriptionId": subscription_id, + "clientSecret": client_secret + } + +@router.post("/subscriptions/verify") +def verify_subscription( + payload: schemas.SubscriptionVerifyRequest, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Direct client-side verification endpoint. + Retrieves the subscription state from Stripe and upgrades the user tier immediately in the DB. + Useful as a fallback or immediate confirmation path before the webhook arrives. + """ + stripe.api_key = STRIPE_SECRET_KEY + try: + subscription = stripe.Subscription.retrieve(payload.subscription_id) + except Exception as e: + logger.error(f"Failed to retrieve subscription from Stripe: {str(e)}") + raise HTTPException(status_code=400, detail="Invalid subscription ID") + + # Check if the subscription belongs to this user or customer + customer_id = subscription.get("customer") + if customer_id != current_user.stripe_customer_id: + raise HTTPException(status_code=403, detail="Subscription does not belong to this user") + + status = subscription.get("status") + if status in ["active", "trialing"]: + from datetime import datetime as dt, timezone as tz + subscription_id = subscription.get("id") + current_user.subscription_id = subscription_id + current_user.subscription_status = status + current_user.subscription_tier = "pro" + current_user.is_premium = True + + current_period_end = subscription.get("current_period_end") + if current_period_end: + current_user.current_period_end = dt.fromtimestamp(current_period_end, tz.utc) + + # Check if transaction already logged + wallet = get_or_create_wallet(db, current_user.id) + existing_tx = db.query(Transaction).filter( + Transaction.wallet_id == wallet.id, + Transaction.reference_id == subscription_id, + Transaction.status == "success" + ).first() + + if not existing_tx: + amount = 4.99 # Fallback amount + # Try to get price from first item + try: + price = subscription["items"]["data"][0]["price"] + amount = (price["unit_amount"] or 0) / 100 + except Exception: + pass + + db.add(Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type="pro_subscription", + status="success", + reference_id=subscription_id, + description=f"Monteeq Pro Subscription Verified (Immediate fallback, USD {amount:.2f})" + )) + + db.commit() + logger.info(f"Stripe verified Pro Upgrade via client verify. User: {current_user.id}") + return {"status": "success", "message": "Subscription verified and upgraded successfully!", "is_premium": True} + else: + logger.warning(f"Subscription status is not active: {status}") + return {"status": "incomplete", "message": f"Subscription status is {status}", "is_premium": False} + +@router.get("/subscription/status", response_model=schemas.SubscriptionStatusResponse) +def get_subscription_status( + current_user: User = Depends(get_current_user) +): + """ + Returns the subscription tier, status, current period end date, and stripe customer id for the user. + """ + cancel_at_period_end = False + if current_user.subscription_id: + try: + stripe.api_key = STRIPE_SECRET_KEY + sub = stripe.Subscription.retrieve(current_user.subscription_id) + cancel_at_period_end = sub.get("cancel_at_period_end", False) + except Exception: + pass + + return { + "status": current_user.subscription_status or "inactive", + "tier": current_user.subscription_tier or "free", + "current_period_end": current_user.current_period_end, + "stripe_customer_id": current_user.stripe_customer_id, + "cancel_at_period_end": cancel_at_period_end + } + +@router.post("/subscriptions/auto-renew") +def toggle_subscription_auto_renew( + payload: schemas.SubscriptionAutoRenewRequest, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Toggles the cancel_at_period_end flag on Stripe to enable/disable auto-renew. + """ + if not current_user.subscription_id: + raise HTTPException(status_code=400, detail="No active subscription found") + + stripe.api_key = STRIPE_SECRET_KEY + try: + sub = stripe.Subscription.modify( + current_user.subscription_id, + cancel_at_period_end=not payload.auto_renew + ) + return { + "status": "success", + "auto_renew": payload.auto_renew, + "message": "Auto-renewal status updated successfully" + } + except Exception as e: + logger.error(f"Failed to toggle auto-renew: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to update auto-renewal: {str(e)}") + +@router.post("/subscriptions/cancel") +def cancel_subscription( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Cancels the user's subscription immediately in Stripe and updates database. + """ + if not current_user.subscription_id: + raise HTTPException(status_code=400, detail="No active subscription found") + + stripe.api_key = STRIPE_SECRET_KEY + try: + stripe.Subscription.cancel(current_user.subscription_id) + + # Downgrade user in DB + current_user.subscription_status = "canceled" + current_user.subscription_tier = "free" + current_user.is_premium = False + db.commit() + + return { + "status": "success", + "message": "Subscription canceled successfully." + } + except Exception as e: + logger.error(f"Failed to cancel subscription: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to cancel subscription: {str(e)}") + +@router.post("/customer-portal", response_model=schemas.CustomerPortalResponse) +def create_customer_portal( + current_user: User = Depends(get_current_user) +): + """ + Generates a Stripe Billing Customer Portal link and returns it. + """ + if not current_user.stripe_customer_id: + raise HTTPException(status_code=400, detail="You do not have a billing history or active customer profile yet") + + stripe.api_key = STRIPE_SECRET_KEY + try: + portal_session = stripe.billing_portal.Session.create( + customer=current_user.stripe_customer_id, + return_url=f"{FRONTEND_URL}/pro" + ) + return {"url": portal_session.url} + except Exception as e: + logger.error(f"Failed to create Stripe Billing Portal session: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to open billing settings: {str(e)}") + +import uuid +@router.post("/pro/initialize", response_model=schemas.PaymentInitializeResponse) +def initialize_pro_subscription( + payload: schemas.PaymentInitialize, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Initializes a Stripe checkout session for Pro Subscription + and saves the pending transaction in the database. + """ + if current_user.is_premium: + raise HTTPException(status_code=400, detail="You are already a Pro member") + + wallet = get_or_create_wallet(db, current_user.id) + + amount = 26400.0 if payload.is_yearly else 2500.0 + stripe_amount_cents = int(amount * 100) + + try: + stripe.api_key = STRIPE_SECRET_KEY + + checkout_session = stripe.checkout.Session.create( + payment_method_types=['card'], + line_items=[{ + 'price_data': { + 'currency': 'ngn', + 'product_data': { + 'name': f"Monteeq Pro {'Yearly' if payload.is_yearly else 'Monthly'}", + 'description': "Access to premium video rendering (4K), Gold Challenges, and 0% commission.", + }, + 'unit_amount': stripe_amount_cents, + }, + 'quantity': 1, + }], + mode='payment', + success_url=f"{FRONTEND_URL}/payment?status=success&reference={{CHECKOUT_SESSION_ID}}", + cancel_url=f"{FRONTEND_URL}/payment?status=cancelled&reference={{CHECKOUT_SESSION_ID}}", + metadata={ + "user_id": str(current_user.id), + "payment_type": "pro_subscription", + "is_yearly": str(payload.is_yearly) + } + ) + reference = checkout_session.id + checkout_url = checkout_session.url + except Exception as e: + logger.error(f"Failed to create Stripe Checkout Session: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to initialize payment gateway: {str(e)}") + + transaction = Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type='pro_subscription', + status='pending', + reference_id=reference, + description=f"Monteeq Pro {'Yearly' if payload.is_yearly else 'Monthly'} Subscription Upgrade (Pending - Stripe)" + ) + db.add(transaction) + db.commit() + db.refresh(transaction) + + return {"reference": reference, "status": "success", "checkout_url": checkout_url} + +@router.post("/verify-pro", response_model=schemas.ProUpgradeResponse) +async def verify_pro_subscription( + payload: schemas.PaymentVerify, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Verify a payment transaction reference (Stripe or Paystack) and upgrade user to Pro. + """ + if current_user.is_premium: + return {"status": "success", "message": "You are already a Pro member!", "is_premium": True} + + is_stripe = payload.reference.startswith("cs_") + + if is_stripe: + try: + stripe.api_key = STRIPE_SECRET_KEY + session = stripe.checkout.Session.retrieve(payload.reference) + except Exception as e: + raise HTTPException(status_code=500, detail=f"Stripe verification failed: {str(e)}") + + if session.payment_status != "paid": + logger.error(f"Stripe verification failed: {session}") + existing = db.query(Transaction).filter(Transaction.reference_id == payload.reference).first() + if existing and existing.status == "pending": + existing.status = "failed" + db.commit() + raise HTTPException(status_code=400, detail="Payment verification failed: Session is unpaid") + + logger.info(f"Stripe verification success for reference: {payload.reference}") + amount = (session.amount_total or 0) / 100 + is_yearly = session.metadata.get("is_yearly") == "True" + else: + # Verify with Paystack + async with httpx.AsyncClient() as client: + try: + response = await client.get( + f"https://api.paystack.co/transaction/verify/{payload.reference}", + headers={"Authorization": f"Bearer {PAYSTACK_SECRET_KEY}"}, + timeout=10.0 + ) + data = response.json() + except Exception as e: + raise HTTPException(status_code=500, detail=f"Paystack verification failed: {str(e)}") + + if not data.get("status") or data.get("data", {}).get("status") != "success": + logger.error(f"Paystack verification failed: {data}") + existing = db.query(Transaction).filter(Transaction.reference_id == payload.reference).first() + if existing and existing.status == "pending": + existing.status = "failed" + db.commit() + error_msg = data.get("data", {}).get("gateway_response") or data.get("message", "Unknown error") + raise HTTPException(status_code=400, detail=f"Payment verification failed: {error_msg}") + + logger.info(f"Paystack verification success for reference: {payload.reference}") + try: + amount = data["data"]["amount"] / 100 + except (KeyError, TypeError): + amount = 0.0 + logger.error(f"Could not extract amount for pro verify ref={payload.reference}") + is_yearly = amount >= 20000 + + # 3. Upgrade User + from datetime import datetime, timedelta, timezone + current_user.is_premium = True + if is_yearly: + current_user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=365) + else: + current_user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=30) + + # 4. Record Transaction (Idempotency) + existing = db.query(Transaction).filter(Transaction.reference_id == payload.reference).first() + if existing: + if existing.status != "success": + existing.status = "success" + existing.amount = amount + else: + wallet = get_or_create_wallet(db, current_user.id) + transaction = Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type='pro_subscription', + status='success', + reference_id=payload.reference, + description="Monteeq Pro Subscription Upgrade" + ) + db.add(transaction) + + db.commit() + db.refresh(current_user) + + logger.info(f"User {current_user.id} upgraded to premium. is_premium: {current_user.is_premium}") + + return { + "status": "success", + "message": "Welcome to Monteeq Pro! Your account has been upgraded.", + "is_premium": True + } + + +@router.post("/deposit/verify", response_model=schemas.Transaction) +async def verify_deposit_and_fund( + payload: schemas.PaymentVerify, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Verify a transaction reference (Stripe or Paystack) and fund the user's wallet or upgrade to Pro. + """ + is_stripe = payload.reference.startswith("cs_") + + if is_stripe: + try: + stripe.api_key = STRIPE_SECRET_KEY + session = stripe.checkout.Session.retrieve(payload.reference) + except Exception as e: + logger.error(f"Stripe API error for ref {payload.reference}: {str(e)}") + raise HTTPException(status_code=500, detail=f"Stripe verification failed: {str(e)}") + + if session.payment_status != "paid": + logger.warning(f"Stripe verification failed for ref {payload.reference}: session unpaid") + raise HTTPException(status_code=400, detail="Payment verification failed: Session is unpaid") + + amount = (session.amount_total or 0) / 100 + payment_type = session.metadata.get("payment_type", "deposit") + + wallet = get_or_create_wallet(db, current_user.id) + + if payment_type == "pro_subscription": + # Upgrade user to Pro + is_yearly = session.metadata.get("is_yearly") == "True" + from datetime import datetime, timedelta, timezone + current_user.is_premium = True + if is_yearly: + current_user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=365) + else: + current_user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=30) + + # Record / update transaction + existing = db.query(Transaction).filter(Transaction.reference_id == payload.reference).first() + if existing: + if existing.status != "success": + existing.status = "success" + existing.amount = amount + transaction = existing + else: + transaction = Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type='pro_subscription', + status='success', + reference_id=payload.reference, + description="Monteeq Pro Subscription Upgrade" + ) + db.add(transaction) + db.commit() + db.refresh(transaction) + logger.info(f"Stripe verified Pro Upgrade via deposit verify. User: {current_user.id}") + return transaction + else: + # Wallet deposit + existing = db.query(Transaction).filter(Transaction.reference_id == payload.reference).first() + if existing: + return existing + from decimal import Decimal + wallet.balance += Decimal(str(amount)) + transaction = Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type='deposit', + reference_id=payload.reference, + description="Wallet Top-up via Stripe" + ) + db.add(transaction) + db.add(wallet) + db.commit() + db.refresh(transaction) + logger.info(f"Stripe verified Wallet Deposit via deposit verify. User: {current_user.id}, amount: {amount}") + return transaction + + else: + # Paystack verification flow + async with httpx.AsyncClient() as client: + try: + response = await client.get( + f"https://api.paystack.co/transaction/verify/{payload.reference}", + headers={"Authorization": f"Bearer {PAYSTACK_SECRET_KEY}"}, + timeout=10.0 + ) + data = response.json() + logger.info(f"Paystack verification response for ref {payload.reference}: {data}") + except Exception as e: + logger.error(f"Paystack API error for ref {payload.reference}: {str(e)}") + raise HTTPException(status_code=500, detail=f"Paystack verification failed: {str(e)}") + + if not data.get("status") or data.get("data", {}).get("status") != "success": + logger.warning(f"Paystack verification failed for ref {payload.reference}: {data}") + error_msg = data.get('data', {}).get('gateway_response') or data.get('message', 'Unknown error') + raise HTTPException(status_code=400, detail=f"Payment verification failed: {error_msg}") + + try: + amount = data["data"]["amount"] / 100 # Convert kobo to NGN + except (KeyError, TypeError): + logger.error(f"Failed to extract amount from Paystack response for ref {payload.reference}: {data}") + raise HTTPException(status_code=500, detail="Invalid data received from Paystack") + + # Check if Paystack metadata says pro_subscription + meta = data.get("data", {}).get("metadata") or {} + payment_type = meta.get("payment_type", "deposit") + + if payment_type == "pro_subscription": + wallet = get_or_create_wallet(db, current_user.id) + is_yearly = meta.get("billing_cycle") == "yearly" or amount >= 20000 + from datetime import datetime, timedelta, timezone + current_user.is_premium = True + if is_yearly: + current_user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=365) + else: + current_user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=30) + + existing = db.query(Transaction).filter(Transaction.reference_id == payload.reference).first() + if existing: + if existing.status != "success": + existing.status = "success" + existing.amount = amount + transaction = existing + else: + transaction = Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type='pro_subscription', + status='success', + reference_id=payload.reference, + description="Monteeq Pro Subscription Upgrade" + ) + db.add(transaction) + db.commit() + db.refresh(transaction) + return transaction + else: + from app.crud.monetization import verify_deposit + transaction = verify_deposit(db, user_id=current_user.id, amount=amount, reference=payload.reference) + logger.info(f"Deposit verified OK. Transaction ID: {transaction.id}") + return transaction + + + +# ================================================================== # +# PAYSTACK WEBHOOK # +# POST /api/v1/monetization/webhook/paystack # +# # +# Register in Paystack Dashboard: # +# Settings → API Keys & Webhooks → Webhook URL # +# ================================================================== # + +@router.post("/webhook/paystack", status_code=200) +async def paystack_webhook(request: Request, db: Session = Depends(get_db)): + """ + Server-side Paystack event receiver (HMAC-SHA512 verified). + + Supported events: + - charge.success → pro_subscription upgrade OR wallet deposit + + The frontend must pass these fields in Paystack's metadata when + initialising a transaction so the webhook can route correctly: + metadata: { user_id: , payment_type: "pro_subscription" | "deposit" } + """ + # ── 1. Read raw body BEFORE any parsing (required for valid HMAC) ── + raw_body = await request.body() + + # ── 2. Verify Paystack HMAC-SHA512 signature ──────────────────────── + paystack_sig = request.headers.get("x-paystack-signature", "") + expected_sig = hmac.new( + PAYSTACK_SECRET_KEY.encode("utf-8"), + raw_body, + hashlib.sha512 + ).hexdigest() + + if not hmac.compare_digest(paystack_sig, expected_sig): + logger.warning("Paystack webhook: invalid HMAC signature — request rejected") + raise HTTPException(status_code=401, detail="Invalid webhook signature") + + # ── 3. Parse event payload ─────────────────────────────────────────── + try: + event = json.loads(raw_body) + except Exception: + raise HTTPException(status_code=400, detail="Invalid JSON payload") + + event_type = event.get("event") + data = event.get("data", {}) + reference = data.get("reference") + meta = data.get("metadata") or {} + logger.info(f"Paystack webhook received: event={event_type}, ref={reference}") + + # ── 4. Handle charge.success ───────────────────────────────────────── + if event_type == "charge.success" and data.get("status") == "success": + + # Idempotency guard — skip if already processed + existing = db.query(Transaction).filter( + Transaction.reference_id == reference + ).first() + if existing: + logger.info(f"Paystack webhook: ref {reference} already processed, skipping") + return {"status": "ok", "message": "already_processed"} + + amount_ngn = data.get("amount", 0) / 100 # kobo → NGN + payment_type = meta.get("payment_type", "deposit") + user_id = meta.get("user_id") + + # Fallback: resolve user by customer email if metadata missing user_id + if not user_id: + customer_email = data.get("customer", {}).get("email") + if customer_email: + u = db.query(User).filter(User.email == customer_email).first() + user_id = u.id if u else None + + if not user_id: + logger.error(f"Paystack webhook: cannot determine user for ref={reference}") + # Return 200 so Paystack stops retrying — nothing we can do without a user + return {"status": "ok", "message": "user_not_found"} + + user = db.query(User).filter(User.id == int(user_id)).first() + if not user: + logger.error(f"Paystack webhook: user_id={user_id} not in DB for ref={reference}") + return {"status": "ok", "message": "user_not_found"} + + wallet = get_or_create_wallet(db, user.id) + + if payment_type == "pro_subscription": + from datetime import datetime, timedelta, timezone + if not user.is_premium: + user.is_premium = True + + if amount_ngn >= 20000: + user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=365) + else: + user.premium_expires_at = datetime.now(timezone.utc) + timedelta(days=30) + + existing_tx = db.query(Transaction).filter(Transaction.reference_id == reference).first() + if existing_tx: + if existing_tx.status != "success": + existing_tx.status = "success" + existing_tx.amount = amount_ngn + else: + db.add(Transaction( + wallet_id=wallet.id, + amount=amount_ngn, + transaction_type="pro_subscription", + status="success", + reference_id=reference, + description="Monteeq Pro Subscription (Paystack webhook)" + )) + db.commit() + logger.info(f"Paystack webhook: user {user.id} upgraded to Pro via ref={reference}") + + else: # wallet deposit (default) + from decimal import Decimal + wallet.balance += Decimal(str(amount_ngn)) + db.add(Transaction( + wallet_id=wallet.id, + amount=amount_ngn, + transaction_type="deposit", + reference_id=reference, + description=f"Wallet top-up via Paystack (₦{amount_ngn:,.2f})" + )) + db.commit() + logger.info(f"Paystack webhook: ₦{amount_ngn:,.2f} credited to user {user.id} wallet, ref={reference}") + + else: + logger.info(f"Paystack webhook: unhandled event type '{event_type}' — ignored") + + # Always return 200 to stop Paystack from retrying + return {"status": "ok"} + + +# ================================================================== # +# PAYSTACK CALLBACK / FALLBACK URL # +# GET /api/v1/monetization/payment/callback # +# # +# Register in Paystack Dashboard: # +# Settings → API Keys & Webhooks → Callback URL # +# ================================================================== # + +@router.get("/payment/callback") +async def paystack_callback( + reference: str = None, + trxref: str = None, +): + """ + Browser redirect fallback after Paystack hosted-page checkout. + + Paystack appends ?reference=xxx&trxref=xxx to this URL after the + user completes or cancels payment on the hosted checkout page. + We redirect them to the frontend /payment page with the reference + so the UI can call /deposit/verify or /verify-pro to confirm. + """ + ref = reference or trxref + frontend = FRONTEND_URL.rstrip("/") + + if not ref: + redirect_target = f"{frontend}/payment?status=cancelled" + else: + redirect_target = f"{frontend}/payment?status=pending&reference={ref}" + + logger.info(f"Paystack callback: ref={ref} → {redirect_target}") + return RedirectResponse(url=redirect_target, status_code=302) + + +# ================================================================== # +# STRIPE WEBHOOK # +# POST /api/v1/monetization/webhook/stripe # +# ================================================================== # + +@router.post("/webhook/stripe", status_code=200) +async def stripe_webhook(request: Request, db: Session = Depends(get_db)): + """ + Server-side Stripe event receiver (verified using signature). + """ + from datetime import datetime as dt, timezone as tz, timedelta + + payload = await request.body() + sig_header = request.headers.get("stripe-signature") + + if not sig_header: + logger.warning("Stripe webhook: missing stripe-signature header") + raise HTTPException(status_code=400, detail="Missing stripe-signature header") + + try: + stripe.api_key = STRIPE_SECRET_KEY + event = stripe.Webhook.construct_event( + payload, sig_header, STRIPE_WEBHOOK_SECRET + ) + except ValueError as e: + logger.warning(f"Stripe webhook: invalid payload: {str(e)}") + raise HTTPException(status_code=400, detail="Invalid payload") + except stripe.signature.SignatureVerificationError as e: + logger.warning(f"Stripe webhook: signature verification failed: {str(e)}") + raise HTTPException(status_code=400, detail="Invalid signature") + + event_type = event.get("type") + logger.info(f"Stripe webhook received: event={event_type}") + + # Handle subscription events + if event_type in ["customer.subscription.created", "customer.subscription.updated"]: + subscription = event.get("data", {}).get("object", {}) + subscription_id = subscription.get("id") + customer_id = subscription.get("customer") + status = subscription.get("status") + current_period_end_timestamp = subscription.get("current_period_end") + + user = db.query(User).filter(User.stripe_customer_id == customer_id).first() + if user: + user.subscription_id = subscription_id + user.subscription_status = status + if current_period_end_timestamp: + user.current_period_end = dt.fromtimestamp(current_period_end_timestamp, tz.utc) + + if status == "active": + user.subscription_tier = "pro" + user.is_premium = True + elif status in ["unpaid", "canceled", "incomplete_expired"]: + user.is_premium = False + db.commit() + logger.info(f"Stripe webhook: updated subscription {subscription_id} for user {user.id} to status={status}") + + elif event_type == "customer.subscription.deleted": + subscription = event.get("data", {}).get("object", {}) + subscription_id = subscription.get("id") + user = db.query(User).filter(User.subscription_id == subscription_id).first() + if user: + user.subscription_status = "canceled" + user.is_premium = False + db.commit() + logger.info(f"Stripe webhook: deleted subscription {subscription_id} for user {user.id}") + + elif event_type == "invoice.paid": + invoice = event.get("data", {}).get("object", {}) + subscription_id = invoice.get("subscription") + if subscription_id: + user = db.query(User).filter(User.subscription_id == subscription_id).first() + if user: + user.subscription_status = "active" + user.subscription_tier = "pro" + user.is_premium = True + + amount = (invoice.get("amount_paid") or 0) / 100 + wallet = get_or_create_wallet(db, user.id) + db.add(Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type="pro_subscription", + status="success", + reference_id=invoice.get("charge") or subscription_id, + description=f"Monteeq Pro Subscription Invoice Paid (Stripe webhook, USD {amount:.2f})" + )) + db.commit() + logger.info(f"Stripe webhook: paid invoice for subscription {subscription_id}, user {user.id}") + + elif event_type == "invoice.payment_failed": + invoice = event.get("data", {}).get("object", {}) + subscription_id = invoice.get("subscription") + if subscription_id: + user = db.query(User).filter(User.subscription_id == subscription_id).first() + if user: + user.subscription_status = "past_due" + user.is_premium = False + + amount = (invoice.get("amount_due") or 0) / 100 + wallet = get_or_create_wallet(db, user.id) + db.add(Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type="pro_subscription", + status="failed", + reference_id=invoice.get("id") or subscription_id, + description=f"Monteeq Pro Subscription Invoice Payment Failed (Stripe webhook, USD {amount:.2f})" + )) + db.commit() + logger.warning(f"Stripe webhook: payment failed invoice for subscription {subscription_id}, user {user.id}") + + elif event_type == "checkout.session.completed": + session = event.get("data", {}).get("object", {}) + reference = session.get("id") # Stripe Checkout Session ID + metadata = session.get("metadata", {}) + + # Idempotency guard + existing = db.query(Transaction).filter(Transaction.reference_id == reference).first() + if existing and existing.status == "success": + logger.info(f"Stripe webhook: ref {reference} already processed, skipping") + return {"status": "ok"} + + user_id = metadata.get("user_id") + payment_type = metadata.get("payment_type", "deposit") + is_yearly = metadata.get("is_yearly") == "True" + amount = (session.get("amount_total") or 0) / 100 + + if not user_id: + logger.error(f"Stripe webhook: missing user_id in metadata for session={reference}") + return {"status": "ok", "message": "user_id_missing"} + + user = db.query(User).filter(User.id == int(user_id)).first() + if not user: + logger.error(f"Stripe webhook: user {user_id} not found in DB") + return {"status": "ok", "message": "user_not_found"} + + wallet = get_or_create_wallet(db, user.id) + + if payment_type == "pro_subscription": + user.is_premium = True + user.subscription_tier = "pro" + user.subscription_status = "active" + if is_yearly: + user.premium_expires_at = dt.now(tz.utc) + timedelta(days=365) + user.current_period_end = dt.now(tz.utc) + timedelta(days=365) + else: + user.premium_expires_at = dt.now(tz.utc) + timedelta(days=30) + user.current_period_end = dt.now(tz.utc) + timedelta(days=30) + + existing_tx = db.query(Transaction).filter(Transaction.reference_id == reference).first() + if existing_tx: + if existing_tx.status != "success": + existing_tx.status = "success" + existing_tx.amount = amount + else: + db.add(Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type="pro_subscription", + status="success", + reference_id=reference, + description="Monteeq Pro Subscription (Stripe Checkout webhook)" + )) + db.commit() + logger.info(f"Stripe webhook: user {user.id} upgraded to Pro via reference={reference}") + else: + # Wallet deposit + from decimal import Decimal + existing_tx = db.query(Transaction).filter(Transaction.reference_id == reference).first() + if existing_tx: + if existing_tx.status != "success": + existing_tx.status = "success" + wallet.balance += Decimal(str(amount)) + else: + wallet.balance += Decimal(str(amount)) + db.add(Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type="deposit", + status="success", + reference_id=reference, + description=f"Wallet top-up via Stripe (₦{amount:,.2f})" + )) + db.commit() + logger.info(f"Stripe webhook: credited ₦{amount:,.2f} to user {user.id} wallet, reference={reference}") + + return {"status": "ok"} diff --git a/app/api/v1/endpoints/notifications.py b/app/api/v1/endpoints/notifications.py new file mode 100644 index 0000000000000000000000000000000000000000..bee8aac243f33e8faee3c4bd3f16f338d796e052 --- /dev/null +++ b/app/api/v1/endpoints/notifications.py @@ -0,0 +1,75 @@ +from typing import List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app.core import dependencies +from app.db.session import get_db +from app.crud import notification as crud_notification +from app.models.models import User +from app.schemas import notification as schemas +from app.schemas import push as push_schemas +import os + +router = APIRouter() + +@router.get("/vapid-public-key") +def get_vapid_public_key(): + """Return the VAPID public key so the frontend can subscribe to push notifications.""" + key = os.getenv("VAPID_PUBLIC_KEY", "") + if not key: + raise HTTPException(status_code=503, detail="Push notifications not configured") + return {"public_key": key} + + +@router.get("/unread", response_model=List[schemas.Notification]) +def get_unread_notifications( + db: Session = Depends(get_db), + current_user: User = Depends(dependencies.get_current_user) +): + return crud_notification.get_unread_notifications(db, user_id=current_user.id) + +@router.put("/{notification_id}/read", response_model=schemas.Notification) +def mark_notification_read( + notification_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(dependencies.get_current_user) +): + notification = crud_notification.mark_notification_read(db, notification_id=notification_id, user_id=current_user.id) + if not notification: + raise HTTPException(status_code=404, detail="Notification not found") + return notification + +@router.put("/read-all") +def mark_all_notifications_read( + db: Session = Depends(get_db), + current_user: User = Depends(dependencies.get_current_user) +): + crud_notification.mark_all_notifications_read(db, user_id=current_user.id) + return {"message": "All notifications marked as read"} + +@router.get("/", response_model=List[schemas.Notification]) +def read_notifications( + skip: int = 0, + limit: int = 50, + db: Session = Depends(get_db), + current_user: User = Depends(dependencies.get_current_user) +): + return crud_notification.get_notifications(db, user_id=current_user.id, skip=skip, limit=limit) + +@router.post("/push-subscriptions", response_model=push_schemas.PushSubscription) +def subscribe_push( + subscription: push_schemas.PushSubscriptionCreate, + db: Session = Depends(get_db), + current_user: User = Depends(dependencies.get_current_user) +): + return crud_notification.create_push_subscription(db, subscription=subscription, user_id=current_user.id) + +@router.delete("/push-subscriptions") +def unsubscribe_push( + endpoint: str, + db: Session = Depends(get_db), + current_user: User = Depends(dependencies.get_current_user) +): + success = crud_notification.delete_push_subscription(db, endpoint=endpoint, user_id=current_user.id) + if not success: + raise HTTPException(status_code=404, detail="Subscription not found") + return {"message": "Successfully unsubscribed"} diff --git a/app/api/v1/endpoints/partners.py b/app/api/v1/endpoints/partners.py new file mode 100644 index 0000000000000000000000000000000000000000..ec177c6a8ce621fa36bf88f4cc4520346ce3db49 --- /dev/null +++ b/app/api/v1/endpoints/partners.py @@ -0,0 +1,91 @@ +from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks +from sqlalchemy.orm import Session +from typing import List +import logging + +from app.db.session import get_db +from app.models.models import User, PartnerLead +from app.schemas import schemas +from app.core.dependencies import get_current_user +from app.services.email_service import send_email +from app.core import config + +logger = logging.getLogger(__name__) + +router = APIRouter() + +@router.post("/brief", response_model=schemas.PartnerLead) +async def submit_partner_brief( + payload: schemas.PartnerLeadCreate, + background_tasks: BackgroundTasks, + db: Session = Depends(get_db) +): + """ + Public endpoint for brands to submit campaign briefs. + Saves to DB and sends an email notification to the admin. + """ + lead = PartnerLead( + brand_name=payload.brand_name, + contact_email=payload.contact_email, + campaign_type=payload.campaign_type, + details=payload.details + ) + db.add(lead) + db.commit() + db.refresh(lead) + + # Notify Admin via Email + message = ( + f"New Partnership Brief from {payload.brand_name}.\n\n" + f"Contact: {payload.contact_email}\n" + f"Campaign Type: {payload.campaign_type}\n" + f"Details: {payload.details}\n\n" + "You can view and manage this lead in the Admin Dashboard." + ) + + background_tasks.add_task( + send_email, + to_email=config.SMTP_USER, # Send to the configured admin email + subject=f"New Partner Lead: {payload.brand_name}", + title="New Campaign Brief Received", + message=message, + action_text="View in Dashboard", + action_url="/admin/partners" # Hypothetical admin path + ) + + return lead + +@router.get("/admin/leads", response_model=List[schemas.PartnerLead]) +def get_partner_leads( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Admin-only endpoint to list all partnership leads. + """ + if current_user.role != "admin": + raise HTTPException(status_code=403, detail="Admin access required") + + return db.query(PartnerLead).order_by(PartnerLead.created_at.desc()).all() + +@router.put("/admin/leads/{lead_id}", response_model=schemas.PartnerLead) +def update_lead_status( + lead_id: int, + status: str, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """ + Admin-only endpoint to update the status of a lead. + """ + if current_user.role != "admin": + raise HTTPException(status_code=403, detail="Admin access required") + + lead = db.query(PartnerLead).filter(PartnerLead.id == lead_id).first() + if not lead: + raise HTTPException(status_code=404, detail="Lead not found") + + lead.status = status + db.commit() + db.refresh(lead) + return lead diff --git a/app/api/v1/endpoints/posts.py b/app/api/v1/endpoints/posts.py new file mode 100644 index 0000000000000000000000000000000000000000..ec5277c6e8d7e58af875000432d1d5e5cf9e359a --- /dev/null +++ b/app/api/v1/endpoints/posts.py @@ -0,0 +1,253 @@ +from fastapi import APIRouter, Depends, HTTPException, status, File, UploadFile, Form, BackgroundTasks +from sqlalchemy.orm import Session +from typing import List, Optional +from uuid import uuid4 + +from app.db.session import get_db, SessionLocal +from app.core.dependencies import get_current_user, get_current_user_optional +from app.schemas import schemas +from app.core import config +from app.models.models import Post, Follow, Like, Comment, User +from app.crud import video as crud_video +from sqlalchemy import case, func + +router = APIRouter() + +@router.get("/", response_model=List[schemas.Post]) +def get_posts( + skip: int = 0, + limit: int = 20, + db: Session = Depends(get_db), + current_user: Optional[dict] = Depends(get_current_user_optional) +): + limit = min(limit, 3) + query = db.query(Post) + + if current_user: + # Get IDs of people user follows + following_ids = db.query(Follow.following_id).filter(Follow.follower_id == current_user.id).all() + following_ids = [f[0] for f in following_ids] + + if following_ids: + is_followed = case( + (Post.owner_id.in_(following_ids), 1), + else_=0 + ).label('is_followed') + query = query.order_by(is_followed.desc(), Post.id.desc()) + else: + query = query.order_by(Post.id.desc()) + else: + query = query.order_by(Post.id.desc()) + + posts = query.offset(skip).limit(limit).all() + + # Advanced Viral Expansion & Discovery + if len(posts) < limit: + remaining = limit - len(posts) + seen_ids = [p.id for p in posts] + + # Pull high engagement posts as fallback + exp_query = db.query(Post).filter(Post.id.notin_(seen_ids), Post.views_count > 5) + remaining_posts = exp_query.order_by(Post.views_count.desc()).limit(remaining).all() + posts.extend(remaining_posts) + + # Populate metadata & handle engagement attribution + for post in posts: + # Determine the target for engagement attribution + target = post + if post.original_post_id and post.original_post: + target = post.original_post + + # Metadata counts always reflect the ORIGINAL post + target.likes_count = db.query(func.count(Like.id)).filter(Like.post_id == target.id).scalar() or 0 + target.comments_count = db.query(func.count(Comment.id)).filter(Comment.post_id == target.id).scalar() or 0 + + if current_user: + target.liked_by_user = db.query(Like).filter(Like.post_id == target.id, Like.user_id == current_user.id).first() is not None + else: + target.liked_by_user = False + + # Increment View on Original + crud_video.increment_view(db, user_id=current_user.id if current_user else None, post_id=target.id) + + db.commit() + return posts + +@router.post("/create", response_model=schemas.Post) +async def create_post( + content: str = Form(...), + tags: Optional[str] = Form(None), + image: Optional[UploadFile] = File(None), + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + image_url = None + if image: + from app.core.storage import storage + import time + + file_ext = image.filename.split(".")[-1] + timestamp = int(time.time()) + s3_key = f"posts/{current_user.id}_{timestamp}.{file_ext}" + + try: + image_url = storage.upload_file_obj(image.file, s3_key) + except Exception as e: + print(f"Failed to upload post image to S3: {e}") + raise HTTPException(status_code=500, detail="Failed to upload image to cloud storage") + + post_in = schemas.PostCreate(content=content, image_url=image_url, tags=tags) + return crud_video.create_post(db, post=post_in, user_id=current_user.id) + +@router.post("/{post_id}/repost", response_model=schemas.Post) +def repost_post( + post_id: int, + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + original_post = db.query(Post).filter(Post.id == post_id).first() + if not original_post: + raise HTTPException(status_code=404, detail="Post not found") + + # Check if already reposted by this user to avoid spam + existing = db.query(Post).filter(Post.original_post_id == post_id, Post.owner_id == current_user.id).first() + if existing: + return existing + + new_repost = Post( + owner_id=current_user.id, + original_post_id=original_post.id, + is_active=True + ) + db.add(new_repost) + db.commit() + db.refresh(new_repost) + return new_repost + +def handle_post_like_background(user_id: int, post_id: int): + """Background task to handle side effects of a post like.""" + db = SessionLocal() + try: + crud_video.handle_like_side_effects(db, user_id, post_id=post_id) + finally: + db.close() + +@router.post("/{post_id}/like") +def like_post( + post_id: int, + background_tasks: BackgroundTasks, + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + post = db.query(Post).filter(Post.id == post_id).first() + if not post: + raise HTTPException(status_code=404, detail="Post not found") + + is_liked = crud_video.toggle_like(db, user_id=current_user.id, post_id=post_id) + + if is_liked: + # Background side effects + background_tasks.add_task(handle_post_like_background, current_user.id, post_id) + + likes_count = db.query(func.count(Like.id)).filter(Like.post_id == post_id).scalar() or 0 + + return {"status": "success", "liked": is_liked, "likes_count": likes_count} + +def handle_post_comment_background(user_id: int, post_id: int): + """Background task for post comment side effects.""" + db = SessionLocal() + try: + crud_video.handle_comment_side_effects(db, user_id, post_id=post_id) + finally: + db.close() + +@router.post("/{post_id}/comment", response_model=schemas.Comment) +def comment_post( + post_id: int, + comment: schemas.CommentCreate, + background_tasks: BackgroundTasks, + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + post = db.query(Post).filter(Post.id == post_id).first() + if not post: + raise HTTPException(status_code=404, detail="Post not found") + + db_comment = crud_video.create_comment(db, comment=comment, user_id=current_user.id, post_id=post_id) + + # Background side effects + background_tasks.add_task(handle_post_comment_background, current_user.id, post_id) + + return db_comment + +@router.get("/{post_id}/comments", response_model=List[schemas.Comment]) +def read_post_comments(post_id: int, db: Session = Depends(get_db), current_user: Optional[User] = Depends(get_current_user_optional)): + return crud_video.get_comments(db, post_id=post_id, current_user_id=current_user.id if current_user else None) + +@router.delete("/{post_id}") +def delete_post( + post_id: int, + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + post = db.query(Post).filter(Post.id == post_id).first() + if not post: + raise HTTPException(status_code=404, detail="Post not found") + + # Check ownership or admin + if post.owner_id != current_user.id and current_user.role != "admin": + raise HTTPException(status_code=403, detail="Not authorized to delete this post") + + # Delete local image if exists + if post.image_url and post.image_url.startswith(config.BASE_URL): + import os + relative_path = post.image_url.replace(f"{config.BASE_URL}/static/", "") + local_path = os.path.join(config.STATIC_DIR, relative_path.replace("/", os.sep)) + if os.path.exists(local_path): + try: + os.remove(local_path) + except Exception as e: + print(f"Failed to delete post image {local_path}: {e}") + + db.delete(post) + db.commit() + return {"status": "success", "message": "Post deleted successfully"} + +@router.put("/{post_id}/comments/{comment_id}", response_model=schemas.Comment) +def update_comment( + post_id: int, + comment_id: int, + comment_in: schemas.CommentBase, + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + # Verify post exists + post = db.query(Post).filter(Post.id == post_id).first() + if not post: + raise HTTPException(status_code=404, detail="Post not found") + + result = crud_video.update_comment(db, comment_id=comment_id, user_id=current_user.id, content=comment_in.content) + if result is None: + raise HTTPException(status_code=404, detail="Comment not found") + if result is False: + raise HTTPException(status_code=403, detail="Not authorized to edit this comment") + return result + +@router.delete("/{post_id}/comments/{comment_id}") +def delete_comment( + post_id: int, + comment_id: int, + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + # Verify post exists + post = db.query(Post).filter(Post.id == post_id).first() + if not post: + raise HTTPException(status_code=404, detail="Post not found") + + result = crud_video.delete_comment(db, comment_id=comment_id, user_id=current_user.id) + if result is None: + raise HTTPException(status_code=404, detail="Comment not found") + if result is False: + raise HTTPException(status_code=403, detail="Not authorized to delete this comment") + return {"status": "success", "message": "Comment deleted successfully"} diff --git a/app/api/v1/endpoints/recommendations.py b/app/api/v1/endpoints/recommendations.py new file mode 100644 index 0000000000000000000000000000000000000000..06395dd47a6cbf1a99c773c9c76cdd9f4edace14 --- /dev/null +++ b/app/api/v1/endpoints/recommendations.py @@ -0,0 +1,175 @@ +import logging +from datetime import datetime +from typing import List, Literal, Optional + +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException +from pydantic import BaseModel, field_validator +from sqlalchemy.orm import Session + +from app.db.session import get_db +from app.models.models import Video, VideoInteraction +from app.schemas import schemas +from app.core.dependencies import get_current_user, get_current_user_optional +from app.services import recommendation_service as rs + +log = logging.getLogger("monteeq.recommend") +router = APIRouter() + +# Valid video types this engine supports +VALID_TYPES = {"flash", "home"} + + +# ─── Pydantic Schemas ───────────────────────────────────────────────────────── + +class TrackEventIn(BaseModel): + """Payload for a single user-video interaction event.""" + video_id: int + watch_time: float + duration: float = 0.0 + liked: bool = False + skipped: bool = False + replayed: bool = False + timestamp: Optional[datetime] = None + + @field_validator("watch_time", "duration") + @classmethod + def must_be_non_negative(cls, v: float) -> float: + if v < 0: + raise ValueError("watch_time and duration must be >= 0") + return v + + +class TrackEventOut(BaseModel): + interaction_id: int + interaction_score: float + completion_rate: float + skipped_fast: bool + message: str + + +# ─── POST /track ────────────────────────────────────────────────────────────── + +@router.post("/track", response_model=TrackEventOut) +def track_event( + event: TrackEventIn, + background_tasks: BackgroundTasks, + db: Session = Depends(get_db), + current_user=Depends(get_current_user), +): + + user_id: int = current_user.id + + # Fetch only the columns we need for a fast existence check + video_row = ( + db.query(Video.id, Video.duration, Video.video_type) + .filter(Video.id == event.video_id) + .first() + ) + if not video_row: + raise HTTPException(status_code=404, detail="Video not found") + + duration = event.duration if event.duration > 0 else (video_row.duration or 1.0) + + completion_rate, score, skipped_fast = rs.compute_interaction_score( + watch_time=event.watch_time, + duration=duration, + liked=event.liked, + skipped=event.skipped, + replayed=event.replayed, + ) + + interaction = VideoInteraction( + user_id=user_id, + video_id=event.video_id, + watch_time=event.watch_time, + duration=duration, + liked=event.liked, + skipped=event.skipped, + replayed=event.replayed, + completion_rate=completion_rate, + skipped_fast=skipped_fast, + interaction_score=score, + timestamp=event.timestamp or datetime.utcnow(), + ) + db.add(interaction) + db.commit() + db.refresh(interaction) + + rs.record_skip_event(user_id, event.watch_time) + + # Invalidate ALL feed types for this user so both home and flash refresh + rs.invalidate_cache(user_id) + + # Background: update tag-affinity AND watch-history (owns its own DB session) + background_tasks.add_task( + rs.update_user_profile_background, + user_id, + event.video_id, + score, + event.watch_time, + completion_rate, + ) + + log.info( + "[track] user=%d video=%d type=%s score=%.3f completion=%.2f fast_skip=%s", + user_id, event.video_id, video_row.video_type, + score, completion_rate, skipped_fast, + ) + + return TrackEventOut( + interaction_id=interaction.id, + interaction_score=round(score, 4), + completion_rate=round(completion_rate, 4), + skipped_fast=skipped_fast, + message="Event tracked successfully", + ) + + +# ─── GET /feed ──────────────────────────────────────────────────────────────── + +@router.get("/feed", response_model=List[schemas.Video]) +def get_recommended_feed( + video_type: str = "flash", + feed_type: str = "foryou", + limit: int = 20, + mood: Optional[str] = None, + db: Session = Depends(get_db), + current_user=Depends(get_current_user_optional), +): + + if video_type not in VALID_TYPES: + raise HTTPException( + status_code=400, + detail=f"video_type must be one of: {', '.join(sorted(VALID_TYPES))}", + ) + if not (1 <= limit <= 50): + raise HTTPException(status_code=400, detail="limit must be between 1 and 50") + + limit = min(limit, 20) + + if current_user: + feed = rs.build_feed( + db, + user_id=current_user.id, + video_type=video_type, + feed_type=feed_type, + limit=limit, + mood=mood, + ) + else: + # Guest: trending-heavy + exploration, no personalization + n_trending = round(limit * 0.7) + trending = rs._trending_videos(db, video_type=video_type, history={}, limit=n_trending) + explore = rs._exploration_videos( + db, + video_type=video_type, + history={}, + already_returned_ids=[v.id for v in trending], + limit=limit - len(trending), + prefer_short=False, + ) + feed = trending + explore + for v in feed: + v.liked_by_user = False + + return feed diff --git a/app/api/v1/endpoints/reports.py b/app/api/v1/endpoints/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..74752796a1b63a2f6a898468664a76e748f03179 --- /dev/null +++ b/app/api/v1/endpoints/reports.py @@ -0,0 +1,121 @@ +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select +from sqlalchemy import func +from datetime import datetime, timedelta +from typing import Union + +from app.db.async_session import get_async_db +from app.core.async_dependencies import get_async_current_user +from app.models.models import ContentReport, ModerationAuditLog, Video, Post, Comment +from app.schemas.report import ReportCreate + +router = APIRouter() + +async def get_video_db_async(db: AsyncSession, video_id: Union[int, str]) -> Video: + if isinstance(video_id, str) and not video_id.isdigit(): + result = await db.execute(select(Video).filter(Video.public_id == video_id)) + else: + result = await db.execute(select(Video).filter(Video.id == int(video_id))) + video = result.scalar_one_or_none() + if not video: + raise HTTPException(status_code=404, detail="Video not found") + return video + +@router.post("/", status_code=status.HTTP_201_CREATED) # Note: status_code can be 201 or 200, let's use 201 +@router.post("", status_code=status.HTTP_201_CREATED) +async def create_content_report( + report_in: ReportCreate, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + # 1. Rate Limiting: Max 10 reports per user per hour + one_hour_ago = datetime.utcnow() - timedelta(hours=1) + report_count_query = await db.execute( + select(func.count(ContentReport.id)) + .filter(ContentReport.reporter_id == current_user.id, ContentReport.created_at >= one_hour_ago) + ) + report_count = report_count_query.scalar() or 0 + if report_count >= 10: + raise HTTPException(status_code=429, detail="Too many reports. Please try again later.") + + content_type = report_in.content_type.lower() + content_id = report_in.content_id + reason = report_in.reason + description = report_in.description + + # 2. Resolve target and check duplicate + if content_type in ["video", "flash"]: + video = await get_video_db_async(db, content_id) + + dup_query = await db.execute( + select(ContentReport) + .filter(ContentReport.reporter_id == current_user.id, ContentReport.video_id == video.id) + ) + if dup_query.scalar_one_or_none(): + raise HTTPException(status_code=400, detail="You have already reported this content.") + + new_report = ContentReport( + reporter_id=current_user.id, + content_type=content_type, + video_id=video.id, + reason=reason, + description=description + ) + elif content_type == "post": + post_result = await db.execute(select(Post).filter(Post.id == int(content_id))) + post = post_result.scalar_one_or_none() + if not post: + raise HTTPException(status_code=404, detail="Post not found") + + dup_query = await db.execute( + select(ContentReport) + .filter(ContentReport.reporter_id == current_user.id, ContentReport.post_id == post.id) + ) + if dup_query.scalar_one_or_none(): + raise HTTPException(status_code=400, detail="You have already reported this content.") + + new_report = ContentReport( + reporter_id=current_user.id, + content_type="post", + post_id=post.id, + reason=reason, + description=description + ) + elif content_type == "comment": + comment_result = await db.execute(select(Comment).filter(Comment.id == int(content_id))) + comment = comment_result.scalar_one_or_none() + if not comment: + raise HTTPException(status_code=404, detail="Comment not found") + + dup_query = await db.execute( + select(ContentReport) + .filter(ContentReport.reporter_id == current_user.id, ContentReport.comment_id == comment.id) + ) + if dup_query.scalar_one_or_none(): + raise HTTPException(status_code=400, detail="You have already reported this content.") + + new_report = ContentReport( + reporter_id=current_user.id, + content_type="comment", + comment_id=comment.id, + reason=reason, + description=description + ) + else: + raise HTTPException(status_code=400, detail="Invalid content type.") + + # 3. Save to database + db.add(new_report) + + # 4. Audit Trail + audit_log = ModerationAuditLog( + action="report_created", + target_type=content_type, + target_id=str(content_id), + details=f"Report created by user {current_user.username} for reason: {reason}" + ) + db.add(audit_log) + + await db.commit() + return {"message": "Report submitted successfully."} diff --git a/app/api/v1/endpoints/security_ops.py b/app/api/v1/endpoints/security_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..547a14e2441d6b11f59525da6d0ff979e4bc2e50 --- /dev/null +++ b/app/api/v1/endpoints/security_ops.py @@ -0,0 +1,170 @@ +from fastapi import APIRouter, Depends, HTTPException, status, Body +from sqlalchemy.orm import Session +from typing import List +import pyotp +import qrcode +import io +import base64 +import secrets +import json +import hashlib +from app.db.session import get_db +from app.core.dependencies import get_current_user +from app.models.models import User, UserSession +from app.schemas import schemas +from app.core.config import BASE_URL + +router = APIRouter() + +@router.post("/me/2fa/setup") +def setup_totp( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Generate a new TOTP secret and return the provisioning URI (QR code).""" + if current_user.totp_secret: + # User already has 2FA set up (or at least a secret) + pass # We allow re-setup + + secret = pyotp.random_base32() + current_user.totp_secret = secret + db.commit() + + # Generate provisioning URI + uri = pyotp.totp.TOTP(secret).provisioning_uri( + name=current_user.email, + issuer_name="Monteeq" + ) + + # Generate QR Code as base64 + img = qrcode.make(uri) + buffered = io.BytesIO() + img.save(buffered, format="PNG") + img_str = base64.b64encode(buffered.getvalue()).decode() + + return {"qr_code": f"data:image/png;base64,{img_str}", "uri": uri, "secret": secret} + +@router.post("/me/2fa/verify") +def verify_and_enable_totp( + code: str = Body(..., embed=True), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Verify the first TOTP code and enable 2FA for the account.""" + if not current_user.totp_secret: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="2FA setup not initialized" + ) + + totp = pyotp.TOTP(current_user.totp_secret) + if totp.verify(code): + current_user.two_factor_enabled = True + db.commit() + return {"message": "2FA enabled successfully"} + else: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid verification code" + ) + +@router.post("/me/2fa/disable") +def disable_totp( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Disable TOTP 2FA.""" + current_user.two_factor_enabled = False + current_user.totp_secret = None + db.commit() + return {"message": "2FA disabled successfully"} + +@router.get("/me/sessions", response_model=List[schemas.SessionOut]) +def get_sessions( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """List active sessions for the current user.""" + sessions = db.query(UserSession).filter(UserSession.user_id == current_user.id).order_by(UserSession.last_active.desc()).all() + + return [ + schemas.SessionOut( + id=s.id, + device_info=s.device_info or "Unknown Device", + ip_address=s.ip_address or "Unknown IP", + last_active=s.last_active, + is_current=False # logic later + ) for s in sessions + ] + +@router.delete("/me/sessions/{session_id}") +def revoke_session( + session_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Revoke a specific session.""" + session = db.query(UserSession).filter( + UserSession.id == session_id, + UserSession.user_id == current_user.id + ).first() + + if not session: + raise HTTPException(status_code=404, detail="Session not found") + + db.delete(session) + db.commit() + return {"message": "Session revoked"} + +@router.post("/me/deactivate") +def deactivate_account( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Deactivate the current user's account.""" + current_user.is_active = False + db.commit() + return {"message": "Account deactivated"} + +@router.post("/me/2fa/recovery-codes", response_model=List[str]) +def generate_recovery_codes( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Generate 10 new recovery codes and replace old ones.""" + codes = [] + hashed_codes = [] + for _ in range(10): + # Format: XXXX-XXXX-XXXX + code = secrets.token_hex(6).upper() + formatted_code = f"{code[:4]}-{code[4:8]}-{code[8:]}" + codes.append(formatted_code) + + # Store clean hash (no dashes, upper) + clean_code = code.upper() + hashed_codes.append(hashlib.sha256(clean_code.encode()).hexdigest()) + + current_user.recovery_codes = json.dumps(hashed_codes) + db.commit() + return codes + +@router.get("/me/2fa/recovery-codes-status") +def check_recovery_codes( + current_user: User = Depends(get_current_user) +): + """Check how many recovery codes are left.""" + if not current_user.recovery_codes: + return {"count": 0} + codes = json.loads(current_user.recovery_codes) + return {"count": len(codes)} + +@router.delete("/me/delete") +def delete_account( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Permanently delete the current user's account and all associated data.""" + # SQLAlchemy cascade will handle related records if configured correctly + db.delete(current_user) + db.commit() + return {"message": "Account deleted forever"} diff --git a/app/api/v1/endpoints/seo.py b/app/api/v1/endpoints/seo.py new file mode 100644 index 0000000000000000000000000000000000000000..2813474f477b788ee9e2d701670ecb6bf03fe3b2 --- /dev/null +++ b/app/api/v1/endpoints/seo.py @@ -0,0 +1,81 @@ +from fastapi import APIRouter, Depends, Response +from sqlalchemy.orm import Session +from app.db.session import get_db +from app.models.models import Video +from app.core import config +import xml.etree.ElementTree as ET +from datetime import datetime + +router = APIRouter() + +BASE_URL = config.FRONTEND_URL.rstrip('/') + +@router.get("/sitemap.xml") +async def get_sitemap(db: Session = Depends(get_db)): + """Generates a standard XML sitemap for general pages.""" + urlset = ET.Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9") + + # Static Public Pages + pages = [ + {"path": "", "priority": "1.0"}, + {"path": "/home", "priority": "0.9"}, + {"path": "/flash", "priority": "0.9"}, + {"path": "/challenges", "priority": "0.8"}, + {"path": "/about", "priority": "0.7"}, + {"path": "/partner", "priority": "0.7"}, + {"path": "/privacy", "priority": "0.5"}, + {"path": "/terms", "priority": "0.5"}, + ] + for page in pages: + url_el = ET.SubElement(urlset, "url") + ET.SubElement(url_el, "loc").text = f"{BASE_URL}{page['path']}" + ET.SubElement(url_el, "changefreq").text = "daily" + ET.SubElement(url_el, "priority").text = page['priority'] + + # Dynamic Video Pages + videos = db.query(Video).filter(Video.status == "approved").all() + for video in videos: + url_el = ET.SubElement(urlset, "url") + ET.SubElement(url_el, "loc").text = f"{BASE_URL}/watch/{video.id}" + ET.SubElement(url_el, "lastmod").text = video.created_at.strftime("%Y-%m-%d") + ET.SubElement(url_el, "changefreq").text = "weekly" + ET.SubElement(url_el, "priority").text = "0.6" + + xml_data = b'\n' + ET.tostring(urlset, encoding="utf-8", method="xml") + return Response(content=xml_data, media_type="application/xml") + +@router.get("/video-sitemap.xml") +async def get_video_sitemap(db: Session = Depends(get_db)): + """Generates a specialized Video XML sitemap for Google Video Indexing.""" + urlset = ET.Element("urlset", { + "xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9", + "xmlns:video": "http://www.google.com/schemas/sitemap-video/1.1" + }) + + videos = db.query(Video).filter(Video.status == "approved").all() + video_ns = "{http://www.google.com/schemas/sitemap-video/1.1}" + + for video in videos: + # Skip videos without necessary data + if not video.created_at or not video.video_url: + continue + + url_el = ET.SubElement(urlset, "url") + ET.SubElement(url_el, "loc").text = f"{BASE_URL}/watch/{video.id}" + + video_el = ET.SubElement(url_el, f"{video_ns}video") + ET.SubElement(video_el, f"{video_ns}thumbnail_loc").text = video.dynamic_thumbnail_url + ET.SubElement(video_el, f"{video_ns}title").text = video.title + ET.SubElement(video_el, f"{video_ns}description").text = video.description or f"Watch {video.title} on Monteeq." + ET.SubElement(video_el, f"{video_ns}content_loc").text = video.dynamic_video_url + ET.SubElement(video_el, f"{video_ns}duration").text = str(video.duration or 60) + + # W3C Format: YYYY-MM-DD (Simplest version) + pub_date = video.created_at.strftime("%Y-%m-%d") + ET.SubElement(video_el, f"{video_ns}publication_date").text = pub_date + + ET.SubElement(video_el, f"{video_ns}family_friendly").text = "yes" + ET.SubElement(video_el, f"{video_ns}live").text = "no" + + xml_data = b'\n' + ET.tostring(urlset, encoding="utf-8", method="xml") + return Response(content=xml_data, media_type="application/xml") diff --git a/app/api/v1/endpoints/users.py b/app/api/v1/endpoints/users.py new file mode 100644 index 0000000000000000000000000000000000000000..8e588fa2a566894ce0682c28550241dcbc933956 --- /dev/null +++ b/app/api/v1/endpoints/users.py @@ -0,0 +1,839 @@ +from fastapi import APIRouter, Depends, HTTPException, status, File, UploadFile, BackgroundTasks +from sqlalchemy.orm import Session +from sqlalchemy import or_, func +from typing import List, Optional +import shutil +import os +import pyotp +import qrcode +import io +import base64 +import secrets +import json +import hashlib +from fastapi import Body + +from app.db.session import get_db, SessionLocal +from app.crud import user as crud_user +from app.schemas import schemas +from app.core.dependencies import get_current_user, get_current_user_optional +from app.core import config +from app.core.storage import storage +from app.models.models import User, Video, Like, Follow, UserSession +from app.core.redis import redis_client +from google.oauth2 import id_token +from google.auth.transport import requests as google_requests + +router = APIRouter() + +@router.get("/me", response_model=schemas.User) +def read_users_me(current_user: schemas.User = Depends(get_current_user)): + return current_user + +@router.put("/me", response_model=schemas.UserUpdateResponse) +def update_user_me( + user_in: schemas.UserUpdate, + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + # Check if username is taken if changing + if user_in.username and user_in.username != current_user.username: + existing_user = crud_user.get_user_by_username(db, username=user_in.username) + if existing_user: + raise HTTPException( + status_code=400, + detail="Username already registered" + ) + + updated_user = crud_user.update_user(db, user_id=current_user.id, user_update=user_in) + + # If username changed, generate new token + access_token = None + if user_in.username and user_in.username != current_user.username: + from app.core.security import create_access_token + from datetime import timedelta + + access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = create_access_token( + data={"sub": user_in.username}, expires_delta=access_token_expires + ) + + return {"user": updated_user, "access_token": access_token} + +@router.put("/me/password") +def update_user_password( + passwords: schemas.PasswordChange, + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + success = crud_user.update_password(db, user_id=current_user.id, passwords=passwords) + if success is None: + raise HTTPException(status_code=404, detail="User not found") + if success is False: + raise HTTPException(status_code=400, detail="Incorrect current password") + + return {"message": "Password updated successfully"} + +@router.get("/profile/{username}", response_model=schemas.UserProfile) +def get_profile( + username: str, + db: Session = Depends(get_db), + current_user: Optional[schemas.User] = Depends(get_current_user_optional) +): + current_user_id = current_user.id if current_user else None + profile = crud_user.get_user_profile(db, username=username, current_user_id=current_user_id) + if not profile: + raise HTTPException(status_code=404, detail="User not found") + return profile + +def handle_follow_background(follower_id: int, following_id: int): + """Background task for follow side effects.""" + db = SessionLocal() + try: + crud_user.handle_follow_side_effects(db, follower_id, following_id) + finally: + db.close() + +@router.post("/follow/{user_id}") +def follow_user( + user_id: int, + background_tasks: BackgroundTasks, + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + is_following = crud_user.toggle_follow(db, follower_id=current_user.id, following_id=user_id) + + if is_following: + # Background side effects (achievements, notifications) + background_tasks.add_task(handle_follow_background, current_user.id, user_id) + + return {"is_following": is_following} + +@router.get("/search", response_model=schemas.UnifiedSearchResponse) +def search_unified( + q: str = "", + db: Session = Depends(get_db) +): + if not q: + return {"videos": [], "users": []} + + # Search for users + users = db.query(User).filter( + or_( + User.username.ilike(f"%{q}%"), + User.full_name.ilike(f"%{q}%") + ) + ).limit(10).all() + + from app.crud import video as crud_video + videos = crud_video.search_videos(db, query_str=q) + posts = crud_video.search_posts(db, query_str=q) + + return {"videos": videos, "users": users, "posts": posts} + +@router.post("/upload-avatar") +async def upload_avatar( + file: UploadFile = File(...), + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + from uuid import uuid4 + + file_ext = file.filename.split(".")[-1] + file_name = f"profiles/{uuid4()}.{file_ext}" + + avatar_url = None + + # Create a temporary local path to save the uploaded file before offloading to S3 + import tempfile + with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_ext}") as tmp: + shutil.copyfileobj(file.file, tmp) + tmp_path = tmp.name + + try: + # Storage Abstraction (Local or S3) + s3_key = f"profiles/{uuid4()}.{file_ext}" + avatar_url = storage.upload_file(tmp_path, s3_key) + finally: + # Clean up temp file + if os.path.exists(tmp_path): + os.remove(tmp_path) + + if not avatar_url: + raise HTTPException(status_code=500, detail="Failed to upload image") + + # Update user in DB + current_user.profile_pic = avatar_url + db.commit() + db.refresh(current_user) + + return {"profile_pic": avatar_url} + +@router.get("/me/insights", response_model=schemas.UserInsights) +def get_user_insights( + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + user_id = current_user.id + import json + cache_key = f"user_insights_{user_id}" + try: + cached = redis_client.get(cache_key) + if cached: + return json.loads(cached) + except Exception: + pass + from app.models.models import Achievement + + # Total Views + total_views = db.query(func.sum(Video.views)).filter(Video.owner_id == user_id).scalar() or 0 + + # Total Likes - Count likes on videos owned by user + total_likes = db.query(func.count(Like.user_id)).join(Video).filter(Video.owner_id == user_id).scalar() or 0 + + # Total Earnings (Disabled) + total_earnings = 0.0 + + # Total Shares + total_shares = db.query(func.sum(Video.shares)).filter(Video.owner_id == user_id).scalar() or 0 + + # Video counts + home_count = db.query(func.count(Video.id)).filter(Video.owner_id == user_id, Video.video_type == "home").scalar() or 0 + flash_count = db.query(func.count(Video.id)).filter(Video.owner_id == user_id, Video.video_type == "flash").scalar() or 0 + + # Post count + from app.models.models import Post + posts_count = db.query(func.count(Post.id)).filter(Post.owner_id == user_id, Post.is_active == True).scalar() or 0 + + # Followers/Following + followers_count = db.query(func.count(Follow.follower_id)).filter(Follow.following_id == user_id).scalar() or 0 + following_count = db.query(func.count(Follow.following_id)).filter(Follow.follower_id == user_id).scalar() or 0 + + # Milestone Logic + milestones = [100, 500, 1000, 5000, 10000, 50000, 100000] + next_milestone = next((m for m in milestones if m > total_views), milestones[-1] * 2) + + # Check for newly reached milestones + existing_achievements = db.query(Achievement).filter(Achievement.user_id == user_id).all() + achieved_names = {a.milestone_name for a in existing_achievements} + + from app.crud import achievement as crud_achievement + new_milestone_reached = None + for m in milestones: + m_name = f"{m}_VIEWS" + if total_views >= m and m_name not in achieved_names: + crud_achievement.create_achievement(db, user_id=user_id, milestone_name=m_name) + new_milestone_reached = m_name + achieved_names.add(m_name) + + # Reload achievements to include any newly created ones + existing_achievements = db.query(Achievement).filter(Achievement.user_id == user_id).all() + + # Top Countries Breakdown + from app.models.models import View + top_countries_query = ( + db.query(User.country, func.count(View.id).label("count")) + .join(View, View.user_id == User.id) + .join(Video, Video.id == View.video_id) + .filter(Video.owner_id == user_id, User.country != None) + .group_by(User.country) + .order_by(func.count(View.id).desc()) + .limit(3) + .all() + ) + top_countries = [{"country": c, "count": cnt} for c, cnt in top_countries_query] + + result = { + "total_views": total_views, + "total_likes": total_likes, + "total_earnings": total_earnings, + "total_shares": total_shares, + "home_videos": home_count, + "flash_videos": flash_count, + "posts_count": posts_count, + "followers": followers_count, + "following": following_count, + "next_milestone": next_milestone, + "new_milestone_reached": new_milestone_reached, + "achievements": [a.milestone_name for a in existing_achievements], + "top_countries": top_countries + } + if redis_client: + try: + redis_client.setex(cache_key, 60, json.dumps(result)) + except Exception: + pass + return result + +@router.get("/me/performance", response_model=schemas.UserPerformance) +def get_user_performance( + metric: str = "views", + days: int = 30, + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + """ + Returns a timeline of performance metrics (views, likes, followers, uploads) + aggregated daily for the last N days. + """ + from datetime import datetime, timedelta + from app.models.models import View, Like, Follow, Video + + user_id = current_user.id + cutoff = datetime.now() - timedelta(days=days) + + # Initialize daily stats dictionary for the range + daily_stats = {} + for i in range(days + 1): + d = (datetime.now() - timedelta(days=i)).date() + daily_stats[d] = {"views": 0, "likes": 0, "followers": 0, "uploads": 0, "earnings": 0.0} + + # 1. Daily Views + view_rows = ( + db.query(func.date(View.created_at).label("d"), func.count(View.id)) + .join(Video, Video.id == View.video_id) + .filter(Video.owner_id == user_id, View.created_at >= cutoff) + .group_by(func.date(View.created_at)) + .all() + ) + for d, count in view_rows: + if d in daily_stats: + daily_stats[d]["views"] = count + + # 2. Daily Likes + like_rows = ( + db.query(func.date(Like.created_at).label("d"), func.count(Like.id)) + .join(Video, Video.id == Like.video_id) + .filter(Video.owner_id == user_id, Like.created_at >= cutoff) + .group_by(func.date(Like.created_at)) + .all() + ) + for d, count in like_rows: + if d in daily_stats: + daily_stats[d]["likes"] = count + + # 3. Daily Followers + follow_rows = ( + db.query(func.date(Follow.created_at).label("d"), func.count(Follow.follower_id)) + .filter(Follow.following_id == user_id, Follow.created_at >= cutoff) + .group_by(func.date(Follow.created_at)) + .all() + ) + for d, count in follow_rows: + if d in daily_stats: + daily_stats[d]["followers"] = count + + # 4. Daily Uploads + upload_rows = ( + db.query(func.date(Video.created_at).label("d"), func.count(Video.id)) + .filter(Video.owner_id == user_id, Video.created_at >= cutoff) + .group_by(func.date(Video.created_at)) + .all() + ) + for d, count in upload_rows: + if d in daily_stats: + daily_stats[d]["uploads"] = count + + # Convert to list of PerformanceDataPoint sorted by date + performance_data = [] + for d in sorted(daily_stats.keys()): + stats = daily_stats[d] + performance_data.append(schemas.PerformanceDataPoint( + date=str(d), + views=stats["views"], + likes=stats["likes"], + followers=stats["followers"], + earnings=stats["earnings"], + uploads=stats["uploads"] + )) + + return {"data": performance_data, "metric": metric} + +@router.get("/me/content-analytics", response_model=list[schemas.ContentAnalyticsItem]) +def get_content_analytics( + limit: int = 10, + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + """Returns top performing videos for the current creator, sorted by views desc.""" + videos = ( + db.query(Video) + .filter(Video.owner_id == current_user.id, Video.status == "approved") + .order_by(Video.views.desc()) + .limit(limit) + .all() + ) + result = [] + for v in videos: + total_interactions = (v.likes_count or 0) + (v.shares or 0) + engagement_rate = round((total_interactions / v.views * 100), 1) if v.views > 0 else 0.0 + result.append(schemas.ContentAnalyticsItem( + id=v.id, + title=v.title, + video_type=v.video_type, + views=v.views or 0, + likes_count=v.likes_count or 0, + shares=v.shares or 0, + engagement_rate=engagement_rate, + )) + return result + +@router.get("/me/audience-split", response_model=schemas.AudienceSplit) +def get_audience_split( + days: int = 30, + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + """ + Returning viewers: users who have watched the creator's videos more than once. + New viewers: users who have watched exactly once in the period. + """ + from datetime import datetime, timedelta + from app.models.models import View + from sqlalchemy import distinct + + cutoff = datetime.now() - timedelta(days=days) + user_id = current_user.id + + # Count views per viewer on this creator's videos in the period + viewer_counts = ( + db.query(View.user_id, func.count(View.id).label("view_count")) + .join(Video, Video.id == View.video_id) + .filter(Video.owner_id == user_id, View.created_at >= cutoff) + .group_by(View.user_id) + .all() + ) + + returning = sum(1 for vc in viewer_counts if vc.view_count > 1) + new = sum(1 for vc in viewer_counts if vc.view_count == 1) + total = sum(vc.view_count for vc in viewer_counts) + + return {"returning_viewers": returning, "new_viewers": new, "total_views": total} + +@router.get("/me/growth-intelligence", response_model=schemas.GrowthIntelligence) +def get_growth_intelligence( + db: Session = Depends(get_db), + current_user: schemas.User = Depends(get_current_user) +): + """ + Computes the Monteeq Growth Score (0–100) and generates real AI growth insights + based on the creator's actual content, engagement, and audience data. + """ + user_id = current_user.id + import json + cache_key = f"growth_intel_{user_id}" + try: + cached = redis_client.get(cache_key) + if cached: + return json.loads(cached) + except Exception: + pass + + from datetime import datetime, timedelta + from app.models.models import View, Like, Follow + import math + now = datetime.now() + cutoff_30 = now - timedelta(days=30) + cutoff_7 = now - timedelta(days=7) + + # ── Raw data ────────────────────────────────────────────────────────────── + videos = db.query(Video).filter( + Video.owner_id == user_id, + Video.status == "approved" + ).order_by(Video.created_at.desc()).all() + + total_videos = len(videos) + total_views = sum(v.views or 0 for v in videos) + total_likes = sum(v.likes_count or 0 for v in videos) + total_shares = sum(v.shares or 0 for v in videos) + + flash_videos = [v for v in videos if v.video_type == "flash"] + home_videos = [v for v in videos if v.video_type == "home"] + + # Videos posted in last 30 days + recent_uploads = [v for v in videos if v.created_at and v.created_at >= cutoff_30] + + # Followers gained last 7 / 30 days + new_followers_7d = db.query(func.count(Follow.follower_id)).filter( + Follow.following_id == user_id, + Follow.created_at >= cutoff_7 + ).scalar() or 0 + + new_followers_30d = db.query(func.count(Follow.follower_id)).filter( + Follow.following_id == user_id, + Follow.created_at >= cutoff_30 + ).scalar() or 0 + + # Audience retention (returning vs new) + viewer_counts = ( + db.query(View.user_id, func.count(View.id).label("vc")) + .join(Video, Video.id == View.video_id) + .filter(Video.owner_id == user_id, View.created_at >= cutoff_30) + .group_by(View.user_id) + .all() + ) + returning_count = sum(1 for vc in viewer_counts if vc.vc > 1) + new_count = sum(1 for vc in viewer_counts if vc.vc == 1) + total_unique = returning_count + new_count + + from sqlalchemy import extract + + # Best day of week for views (0=Sun … 6=Sat for Postgres) + day_view_rows = ( + db.query( + extract('dow', View.created_at).label("dow"), + func.count(View.id).label("cnt") + ) + .join(Video, Video.id == View.video_id) + .filter(Video.owner_id == user_id, View.created_at >= cutoff_30) + .group_by(extract('dow', View.created_at)) + .all() + ) + day_names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + best_day = max(day_view_rows, key=lambda r: r.cnt, default=None) + best_day_name = day_names[int(best_day.dow)] if best_day else None + + # Avg engagement: flash vs home + def avg_views(lst): return sum(v.views or 0 for v in lst) / len(lst) if lst else 0 + def avg_engagement(lst): + if not lst: return 0 + return sum((v.likes_count or 0) + (v.shares or 0) for v in lst) / len(lst) + + flash_avg_views = avg_views(flash_videos) + home_avg_views = avg_views(home_videos) + flash_avg_engage = avg_engagement(flash_videos) + home_avg_engage = avg_engagement(home_videos) + + # Days since last upload + days_since_upload = None + if videos and videos[0].created_at: + days_since_upload = (now - videos[0].created_at).days + + # ── Score Breakdown (each dimension 0–100) ──────────────────────────────── + # 1. Consistency: uploads per week in last 30 days (4 weeks) + uploads_per_week = len(recent_uploads) / 4 + consistency = min(100, int(uploads_per_week / 2 * 100)) # 2 uploads/wk = 100 + + # 2. Engagement: (likes+shares) / views + raw_eng = ((total_likes + total_shares) / total_views) if total_views > 0 else 0 + engagement = min(100, int(raw_eng * 1000)) # 10% ratio = 100 points + + # 3. Retention: returning / total unique + retention = min(100, int((returning_count / total_unique * 100) if total_unique > 0 else 0)) + + # 4. Frequency: total videos (20 = 100) + frequency = min(100, int(total_videos / 20 * 100)) + + # Composite (weighted average) + score = int(0.25*consistency + 0.35*engagement + 0.25*retention + 0.15*frequency) + score = max(0, min(100, score)) + + # ── AI Insights (data-driven strings) ──────────────────────────────────── + insights = [] + + # Insight 1: Flash vs Home performance + if flash_videos and home_videos: + if flash_avg_views > home_avg_views * 1.1: + pct = int((flash_avg_views - home_avg_views) / home_avg_views * 100) + insights.append( + f"Your Flash videos average " + f"{pct}% more views than standard uploads — post more short clips!" + ) + elif home_avg_views > flash_avg_views * 1.1: + pct = int((home_avg_views - flash_avg_views) / flash_avg_views * 100) + insights.append( + f"Your long-form videos outperform " + f"Flash by {pct}% in views — your audience loves depth." + ) + elif flash_videos and not home_videos: + insights.append( + "Try uploading a Home video — " + "mixing formats can grow your audience faster." + ) + + # Insight 2: Best day to post + if best_day_name: + insights.append( + f"Your videos get the most views on " + f"{best_day_name}s — " + f"schedule your next upload then for maximum reach." + ) + + # Insight 3: Follower growth + if new_followers_7d > 0: + insights.append( + f"You gained {new_followers_7d} new " + f"follower{'s' if new_followers_7d != 1 else ''} this week. " + f"Keep posting to maintain momentum." + ) + elif new_followers_30d == 0 and total_videos == 0: + insights.append( + "Upload your first video to start " + "attracting followers and growing your audience." + ) + + # Insight 4: Upload consistency + if days_since_upload is not None and days_since_upload > 7: + insights.append( + f"You haven't posted in {days_since_upload} days. " + f"Creators who post weekly grow followers 3× faster." + ) + elif days_since_upload is not None and days_since_upload <= 3: + insights.append( + "Great upload cadence! Consistent posting " + "is the #1 driver of channel growth on Monteeq." + ) + + # Insight 5: Engagement rate + eng_pct = round(raw_eng * 100, 1) + if eng_pct > 5: + insights.append( + f"Your engagement rate is {eng_pct}% — " + f"well above average. High engagement signals quality content." + ) + elif total_views > 0 and eng_pct < 2: + insights.append( + f"Your engagement rate is {eng_pct}%. " + f"Try adding a call-to-action in your videos to boost likes and shares." + ) + + # Ensure at least one insight + if not insights: + insights.append( + "Upload more content and engage with your audience to unlock " + "personalised growth insights." + ) + + result = { + "score": score, + "breakdown": { + "consistency": consistency, + "engagement": engagement, + "retention": retention, + "frequency": frequency, + }, + "insights": insights[:4], # cap at 4 + } + if redis_client: + try: + redis_client.setex(cache_key, 60, json.dumps(result)) + except Exception: + pass + return result + +@router.put("/me/onboarding", response_model=schemas.User) +def update_onboarding( + onboarding_data: schemas.UserUpdate, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + # Ensure it only updates relevant fields and sets is_onboarded + onboarding_data.is_onboarded = True + updated_user = crud_user.update_user(db, user_id=current_user.id, user_update=onboarding_data) + return updated_user + +@router.post("/me/2fa/setup") +def setup_totp( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Generate a new TOTP secret and return the provisioning URI (QR code).""" + secret = pyotp.random_base32() + current_user.totp_secret = secret + db.commit() + + uri = pyotp.totp.TOTP(secret).provisioning_uri( + name=current_user.email, + issuer_name="Monteeq" + ) + + img = qrcode.make(uri) + buffered = io.BytesIO() + img.save(buffered, format="PNG") + img_str = base64.b64encode(buffered.getvalue()).decode() + + return {"qr_code": f"data:image/png;base64,{img_str}", "uri": uri, "secret": secret} + +@router.post("/me/2fa/verify") +def verify_and_enable_totp( + code: str = Body(..., embed=True), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Verify the first TOTP code and enable 2FA for the account.""" + if not current_user.totp_secret: + raise HTTPException(status_code=400, detail="2FA setup not initialized") + + totp = pyotp.TOTP(current_user.totp_secret) + if totp.verify(code): + current_user.two_factor_enabled = True + db.commit() + return {"message": "2FA enabled successfully"} + else: + raise HTTPException(status_code=400, detail="Invalid verification code") + +@router.post("/me/2fa/disable") +def disable_totp( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Disable TOTP 2FA.""" + current_user.two_factor_enabled = False + current_user.totp_secret = None + db.commit() + return {"message": "2FA disabled successfully"} + +@router.get("/me/sessions", response_model=List[schemas.SessionOut]) +def get_sessions( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """List active sessions for the current user.""" + sessions = db.query(UserSession).filter(UserSession.user_id == current_user.id).order_by(UserSession.last_active.desc()).all() + + return [ + schemas.SessionOut( + id=s.id, + device_info=s.device_info or "Unknown Device", + ip_address=s.ip_address or "Unknown IP", + last_active=s.last_active, + is_current=False + ) for s in sessions + ] + +@router.delete("/me/sessions/{session_id}") +def revoke_session( + session_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Revoke a specific session.""" + session = db.query(UserSession).filter( + UserSession.id == session_id, + UserSession.user_id == current_user.id + ).first() + + if not session: + raise HTTPException(status_code=404, detail="Session not found") + + db.delete(session) + db.commit() + return {"message": "Session revoked"} + +@router.post("/me/deactivate") +def deactivate_account( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Deactivate the current user's account.""" + current_user.is_active = False + db.commit() + return {"message": "Account deactivated"} + +@router.post("/me/2fa/recovery-codes", response_model=List[str]) +def generate_recovery_codes( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Generate 10 new recovery codes and replace old ones.""" + codes = [] + hashed_codes = [] + for _ in range(10): + code = secrets.token_hex(6).upper() + formatted_code = f"{code[:4]}-{code[4:8]}-{code[8:]}" + codes.append(formatted_code) + clean_code = code.upper() + hashed_codes.append(hashlib.sha256(clean_code.encode()).hexdigest()) + + current_user.recovery_codes = json.dumps(hashed_codes) + db.commit() + return codes + +@router.get("/me/2fa/recovery-codes-status") +def check_recovery_codes( + current_user: User = Depends(get_current_user) +): + """Check how many recovery codes are left.""" + if not current_user.recovery_codes: + return {"count": 0} + codes = json.loads(current_user.recovery_codes) + return {"count": len(codes)} + +@router.delete("/me/delete") +def delete_account( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Permanently delete the current user's account and all associated data.""" + db.delete(current_user) + db.commit() + return {"message": "Account deleted forever"} + + +@router.post("/me/link-google", response_model=schemas.User) +def link_google_account( + link_data: schemas.GoogleLinkRequest, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + """Link a Google account to the current user.""" + try: + # 1. Verify Google Token (Access Token or ID Token) + # We call userinfo endpoint which accepts both and returns the 'sub' (Google ID) + import requests + resp = requests.get( + "https://www.googleapis.com/oauth2/v3/userinfo", + headers={"Authorization": f"Bearer {link_data.id_token}"} + ) + + if resp.status_code != 200: + raise HTTPException(status_code=400, detail="Invalid Google token or expired session") + + idinfo = resp.json() + google_id = idinfo['sub'] + + # 2. Check for conflicts + existing_user = db.query(User).filter(User.google_id == google_id).first() + if existing_user and existing_user.id != current_user.id: + raise HTTPException( + status_code=400, + detail="This Google account is already linked to another Monteeq profile." + ) + + # 3. Update user + current_user.google_id = google_id + db.commit() + db.refresh(current_user) + return current_user + + except ValueError: + raise HTTPException(status_code=400, detail="Invalid Google token") + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/{username}/followers", response_model=List[schemas.User]) +def get_user_followers( + username: str, + skip: int = 0, + limit: int = 100, + db: Session = Depends(get_db) +): + user = crud_user.get_user_by_username(db, username=username) + if not user: + raise HTTPException(status_code=404, detail="User not found") + return crud_user.get_followers(db, user_id=user.id, skip=skip, limit=limit) + +@router.get("/{username}/following", response_model=List[schemas.User]) +def get_user_following( + username: str, + skip: int = 0, + limit: int = 100, + db: Session = Depends(get_db) +): + user = crud_user.get_user_by_username(db, username=username) + if not user: + raise HTTPException(status_code=404, detail="User not found") + return crud_user.get_following(db, user_id=user.id, skip=skip, limit=limit) + + diff --git a/app/api/v1/endpoints/video_views.py b/app/api/v1/endpoints/video_views.py new file mode 100644 index 0000000000000000000000000000000000000000..05013d636edc2acee274136f094a127411b0613a --- /dev/null +++ b/app/api/v1/endpoints/video_views.py @@ -0,0 +1,142 @@ +import time +import json +import uuid +import os +from typing import Optional +from fastapi import APIRouter, Depends, HTTPException, Request +from sqlalchemy.orm import Session +from jose import jwt, JWTError +import redis + +from app.db.session import get_db +from app.core import dependencies +from app.crud import video as crud_video +from app.models.models import Video + +router = APIRouter() + +from app.core.redis import redis_client + +# JWT Configuration +SECRET_KEY = os.getenv("SECRET_KEY", "your-super-secret-key") +ALGORITHM = "HS256" +TICKET_EXPIRE_MINUTES = 60 + +def create_view_ticket(video_id: int, user_id: Optional[int], ip: str): + payload = { + "video_id": video_id, + "user_id": user_id, + "ip": ip, + "session_id": str(uuid.uuid4()), + "iat": int(time.time()) + } + return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + +@router.post("/{video_id}/init-view") +async def init_view( + video_id: str, + request: Request, + db: Session = Depends(get_db), + current_user: Optional[dict] = Depends(dependencies.get_current_user_optional) +): + # Bot detection + user_agent = request.headers.get("User-Agent", "").lower() + bot_keywords = ["bot", "crawler", "spider", "google", "bing", "yahoo", "slurp", "headless", "phantom"] + if any(keyword in user_agent for keyword in bot_keywords): + return {"status": "success", "message": "Bot detected, view session not initialized"} + + if isinstance(video_id, str) and not video_id.isdigit(): + video = db.query(Video).filter(Video.public_id == video_id).first() + else: + video = db.query(Video).filter(Video.id == int(video_id)).first() + + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + user_id = current_user.id if current_user else None + ip = request.client.host + + # Rate limiting disabled + + ticket = create_view_ticket(video.id, user_id, ip) + + # Store session in Redis + session_id = str(uuid.uuid4()) + redis_key = f"view_session:{session_id}" + session_data = { + "video_id": video.id, + "accumulated_time": 0, + "last_heartbeat": int(time.time()), + "is_validated": False, + "duration": video.duration or 0 # Fallback if duration not set + } + redis_client.setex(redis_key, 3600, json.dumps(session_data)) + + return {"ticket": ticket, "session_id": session_id} + +@router.post("/{video_id}/heartbeat") +async def view_heartbeat( + video_id: str, + session_id: str, + ticket: str, + db: Session = Depends(get_db) +): + # 1. Validate Ticket + try: + payload = jwt.decode(ticket, SECRET_KEY, algorithms=[ALGORITHM]) + ticket_video_id = payload.get("video_id") + except JWTError: + raise HTTPException(status_code=403, detail="Invalid view ticket") + + if isinstance(video_id, str) and not video_id.isdigit(): + video = db.query(Video).filter(Video.public_id == video_id).first() + else: + video = db.query(Video).filter(Video.id == int(video_id)).first() + + if not video or video.id != ticket_video_id: + raise HTTPException(status_code=400, detail="Invalid ticket for this video") + + # 2. Get Redis Session + redis_key = f"view_session:{session_id}" + raw_session = redis_client.get(redis_key) + if not raw_session: + raise HTTPException(status_code=404, detail="Session expired or invalid") + + session = json.loads(raw_session) + now = int(time.time()) + + # 3. Anti-Spoofing: Check time since last heartbeat + last_hb = session["last_heartbeat"] + delta = now - last_hb + + # Heartbeat expected every 10s. Allow 8s-15s range for network jitter. + if delta < 8: + raise HTTPException(status_code=400, detail="Heartbeat sent too frequently") + + # 4. Update accumulated time + # We only increment by the actual delta (capped at 11s to prevent spoofing) + increment = min(delta, 11) + session["accumulated_time"] += increment + session["last_heartbeat"] = now + + # 5. Validation Check (30s or 80% of video) + threshold = 30 + video_duration = session.get("duration", 0) + if video_duration > 0: + threshold = min(30, int(video_duration * 0.8)) + + if not session["is_validated"] and session["accumulated_time"] >= threshold: + # Commit to DB + crud_video.increment_view(db, video_id=video.id, user_id=payload.get("user_id")) + session["is_validated"] = True + print(f"Video {video.id} view VALIDATED after {session['accumulated_time']}s") + + # Update Redis + redis_client.setex(redis_key, 3600, json.dumps(session)) + + return { + "status": "success", + "accumulated": session["accumulated_time"], + "is_validated": session["is_validated"] + } + diff --git a/app/api/v1/endpoints/videos.py b/app/api/v1/endpoints/videos.py new file mode 100644 index 0000000000000000000000000000000000000000..2468d75f0f36e6e69c664c4924047ea2c734cabf --- /dev/null +++ b/app/api/v1/endpoints/videos.py @@ -0,0 +1,1087 @@ +from typing import List, Optional +import os +import shutil +import tempfile +import httpx +from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, BackgroundTasks, Request +from fastapi.responses import StreamingResponse +import logging +from sqlalchemy import func +from sqlalchemy.orm import Session + +logger = logging.getLogger(__name__) + +from app.db.session import get_db, SessionLocal +from app.crud import video as crud_video +from app.schemas import schemas +from app.core.dependencies import get_current_user, get_current_user_optional +from app.core import config +from app.utils.push import notify_user_push +from app.core.storage import storage +from app.core.config import FLASH_QUOTA_LIMIT, HOME_QUOTA_LIMIT +from app.models.models import Video, User +from app.services.email_service import send_challenge_exit_email +from app.core.redis import redis_client + +from enum import Enum + +class VideoStatus(str, Enum): + UPLOADING = "uploading" + QUEUED = "queued" + PROCESSING = "processing" + READY = "ready" + FAILED = "failed" + +def get_video_db(db: Session, video_id: str) -> Optional[Video]: + if isinstance(video_id, str) and not video_id.isdigit(): + return db.query(Video).filter(Video.public_id == video_id).first() + return db.query(Video).filter(Video.id == int(video_id)).first() + +router = APIRouter() + +@router.get("/health") +async def health_check(db: Session = Depends(get_db)): + health = { + "status": "ok", + "redis": "disconnected", + "database": "disconnected", + "celery": "unknown", + "rust_service": "unknown" + } + + # Check DB + try: + from sqlalchemy import text + db.execute(text("SELECT 1")) + health["database"] = "connected" + except Exception as e: + health["database"] = f"disconnected: {type(e).__name__}: {str(e)}" + health["status"] = "error" + + # Check Redis + try: + if redis_client is None: + health["redis"] = "disconnected: client is None" + health["status"] = "error" + else: + redis_client.ping() + health["redis"] = "connected" + except Exception as e: + health["redis"] = f"disconnected: {type(e).__name__}: {str(e)}" + health["status"] = "error" + + # Check Celery + try: + from app.worker import celery_app + insp = celery_app.control.inspect(timeout=1.0) + ping_res = insp.ping() + if ping_res: + workers = list(ping_res.keys()) + health["celery"] = f"connected ({len(ping_res)} worker(s) active: {', '.join(workers)})" + else: + health["celery"] = "disconnected: no active workers found" + health["status"] = "error" + except Exception as e: + health["celery"] = f"error: {type(e).__name__}: {str(e)}" + health["status"] = "error" + + # Check Rust Service + async with httpx.AsyncClient() as client: + try: + resp = await client.get(f"{config.RUST_SERVICE_URL}/health", timeout=1.0) + if resp.status_code == 200: + health["rust_service"] = "reachable" + except Exception as e: + health["rust_service"] = f"unreachable: {type(e).__name__}: {str(e)}" + + # Check S3 + try: + from app.core.storage import storage + if storage.s3_client is not None: + health["s3"] = "initialized" + else: + health["s3"] = f"not initialized (AWS_ACCESS_KEY_ID = '{config.AWS_ACCESS_KEY_ID[:4]}...' if config.AWS_ACCESS_KEY_ID else 'empty')" + except Exception as e: + health["s3"] = f"error: {type(e).__name__}: {str(e)}" + + return health + +from fastapi_cache.decorator import cache + +@router.get("/", response_model=List[schemas.Video]) +@cache(expire=30) +async def read_videos( + video_type: str = None, + status: str = "approved", + skip: int = 0, + limit: int = 20, + mood: str = None, + feed_mode: str = None, + db: Session = Depends(get_db), + current_user: Optional[dict] = Depends(get_current_user_optional) +): + limit = min(limit, 50) + user_id = current_user.id if current_user else None + videos = crud_video.get_videos(db, video_type=video_type, filter_status=status, current_user_id=user_id, skip=skip, limit=limit, mood=mood, feed_mode=feed_mode) + return videos + + +def check_premium_access(db: Session, request: Request): + token = request.query_params.get("token") + if not token: + auth_header = request.headers.get("Authorization") + if auth_header and auth_header.startswith("Bearer "): + token = auth_header.split(" ")[1] + + if not token: + raise HTTPException(status_code=403, detail="1080p and above quality levels are restricted to Premium members") + + try: + from jose import jwt + from app.core.config import SECRET_KEY, ALGORITHM + from datetime import datetime, timezone + + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get("sub") + if not username: + raise HTTPException(status_code=403, detail="1080p and above quality levels are restricted to Premium members") + + user = db.query(User).filter(User.username == username).first() + if not user or not user.is_active: + raise HTTPException(status_code=403, detail="1080p and above quality levels are restricted to Premium members") + + # Check premium expiration + if user.is_premium and user.premium_expires_at: + if user.premium_expires_at < datetime.now(timezone.utc): + user.is_premium = False + db.commit() + + if not user.is_premium: + raise HTTPException(status_code=403, detail="1080p and above quality levels are restricted to Premium members") + + except Exception: + raise HTTPException(status_code=403, detail="1080p and above quality levels are restricted to Premium members") + + +@router.get("/{video_id}/stream/{sub_path:path}") +@router.get("/{video_id}/stream") +async def stream_video(video_id: str, request: Request, db: Session = Depends(get_db), sub_path: str = None): + # Check premium if quality is high-res (1080p, 2k, 4k) + if sub_path: + sub_path_lower = sub_path.lower() + if "1080p" in sub_path_lower or "2k" in sub_path_lower or "4k" in sub_path_lower: + check_premium_access(db, request) + + video = get_video_db(db, video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + base_url = video.video_url + if not base_url: + raise HTTPException(status_code=400, detail="Video has no URL") + + # Resolve to CDN URL if applicable to avoid S3 DNS timeouts + if "amazonaws.com" in base_url or "monteeq.s3" in base_url or "cdn.monteeq.com" in base_url: + try: + from app.core.storage import storage + if ".com/" in base_url: + parts = base_url.split(".com/") + if len(parts) > 1: + base_url = storage.get_url(parts[1]) + except Exception as e: + logger.warning(f"Failed to resolve CDN URL for streaming: {e}") + + # Construct the proxy target URL + target_url = base_url + if sub_path: + import os + base_dir = os.path.dirname(base_url) + target_url = f"{base_dir}/{sub_path}" + + async def get_stream(): + # read_timeout=None: video files can be large; no upper bound on read time. + # connect_timeout=10s: fail fast if CDN is unreachable. + client = httpx.AsyncClient(timeout=httpx.Timeout(None, connect=10.0)) + range_header = request.headers.get("Range") + headers = { + "User-Agent": "Monteeq-Backend-Proxy/1.0", + } + if range_header: + headers["Range"] = range_header + + try: + req = client.build_request("GET", target_url, headers=headers) + resp = await client.send(req, stream=True) + except httpx.TimeoutException: + await client.aclose() + raise HTTPException(status_code=504, detail="Upstream stream timed out") + except Exception as e: + await client.aclose() + logger.error(f"Stream proxy failed for video {video_id}: {e}") + raise HTTPException(status_code=502, detail="Failed to connect to video source") + + # Check for upstream errors before proxying + if resp.status_code >= 400: + error_status = resp.status_code + await resp.aclose() + await client.aclose() + raise HTTPException(status_code=error_status, detail=f"Video source returned {error_status}") + + # Build headers — Content-Encoding: identity tells GZip middleware to skip + # buffering this response (critical for large video streams). + response_headers = { + "Accept-Ranges": "bytes", + "Content-Encoding": "identity", + } + content_type = resp.headers.get("Content-Type") + if content_type: + response_headers["Content-Type"] = content_type + + content_length = resp.headers.get("Content-Length") + if content_length: + response_headers["Content-Length"] = content_length + + content_range = resp.headers.get("Content-Range") + if content_range: + response_headers["Content-Range"] = content_range + + return StreamingResponse( + resp.aiter_bytes(chunk_size=65536), + status_code=resp.status_code, + headers=response_headers, + background=BackgroundTasks([resp.aclose, client.aclose]) + ) + + return await get_stream() + + +@router.get("/{video_id}/stream-res") +async def stream_video_resolution( + video_id: str, + quality: str, + request: Request, + db: Session = Depends(get_db) +): + """Proxy a specific resolution stream (480p, 720p, 1080p, 2k, 4k) for a video.""" + if quality.lower() in ["1080p", "2k", "4k"]: + check_premium_access(db, request) + + video = get_video_db(db, video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + quality_map = { + "480p": video.url_480p, + "720p": video.url_720p, + "1080p": video.url_1080p, + "2k": video.url_2k, + "4k": video.url_4k, + } + + target_url = quality_map.get(quality.lower()) + if not target_url: + raise HTTPException(status_code=404, detail=f"No {quality} stream available for this video") + + # Resolve CDN URL if needed + if "amazonaws.com" in target_url or "monteeq.s3" in target_url or "cdn.monteeq.com" in target_url: + try: + from app.core.storage import storage + if ".com/" in target_url: + parts = target_url.split(".com/") + if len(parts) > 1: + target_url = storage.get_url(parts[1]) + except Exception as e: + logger.warning(f"Failed to resolve CDN URL for resolution stream: {e}") + + async def get_res_stream(): + # read_timeout=None: no upper bound on read — video files can be large. + client = httpx.AsyncClient(timeout=httpx.Timeout(None, connect=10.0)) + range_header = request.headers.get("Range") + headers = {"User-Agent": "Monteeq-Backend-Proxy/1.0"} + if range_header: + headers["Range"] = range_header + + try: + req = client.build_request("GET", target_url, headers=headers) + resp = await client.send(req, stream=True) + except httpx.TimeoutException: + await client.aclose() + raise HTTPException(status_code=504, detail="Upstream stream timed out") + except Exception as e: + await client.aclose() + logger.error(f"Resolution stream proxy failed for video {video_id} @ {quality}: {e}") + raise HTTPException(status_code=502, detail="Failed to connect to video source") + + if resp.status_code >= 400: + error_status = resp.status_code + await resp.aclose() + await client.aclose() + raise HTTPException(status_code=error_status, detail=f"Video source returned {error_status}") + + # Content-Encoding: identity prevents GZip middleware from buffering the stream. + response_headers = { + "Accept-Ranges": "bytes", + "Content-Encoding": "identity", + } + content_type = resp.headers.get("Content-Type") + if content_type: + response_headers["Content-Type"] = content_type + content_length = resp.headers.get("Content-Length") + if content_length: + response_headers["Content-Length"] = content_length + content_range = resp.headers.get("Content-Range") + if content_range: + response_headers["Content-Range"] = content_range + + return StreamingResponse( + resp.aiter_bytes(chunk_size=65536), + status_code=resp.status_code, + headers=response_headers, + background=BackgroundTasks([resp.aclose, client.aclose]) + ) + + return await get_res_stream() + + +@router.get("/search", response_model=List[schemas.Video]) +async def search_videos( + q: Optional[str] = "", + db: Session = Depends(get_db), + current_user: Optional[dict] = Depends(get_current_user_optional) +): + user_id = current_user.id if current_user else None + return crud_video.search_videos(db, query_str=q, current_user_id=user_id) + +@router.get("/suggestions") +async def get_search_suggestions(q: Optional[str] = "", db: Session = Depends(get_db)): + if not q or len(q) < 2: return [] + + # 1. Search Videos (Home & Flash) + videos = crud_video.search_videos(db, query_str=q) + + # 2. Search Users + from app.models.models import User + users = db.query(User).filter(User.username.ilike(f"%{q}%")).limit(5).all() + + seen = set() + suggestions = [] + + # Prioritize users in suggestions + for u in users: + val = f"@{u.username}" + if val not in seen: + suggestions.append(val) + seen.add(val) + + for v in videos[:10]: + if v.title not in seen: + suggestions.append(v.title) + seen.add(v.title) + + return suggestions[:10] + +@router.get("/trending-suggestions") +async def get_trending_suggestions(db: Session = Depends(get_db)): + import json + + try: + cached = redis_client.get("trending_suggestions") + if cached: + return json.loads(cached) + except Exception: + pass + + # 1. High views (Trending) + trending_videos = db.query(Video).filter(Video.status == "approved").order_by(Video.views.desc()).limit(5).all() + + # 2. Recent uploads + recent_videos = db.query(Video).filter(Video.status == "approved").order_by(Video.created_at.desc()).limit(5).all() + + # 3. Popular Creators + from app.models.models import User + users = db.query(User).limit(3).all() + + seen = set() + suggestions = [] + + for v in trending_videos: + if v.title not in seen: + suggestions.append(v.title) + seen.add(v.title) + + for v in recent_videos: + if v.title not in seen: + suggestions.append(v.title) + seen.add(v.title) + + for u in users: + val = f"@{u.username}" + if val not in seen: + suggestions.append(val) + seen.add(val) + + result = suggestions[:10] + try: + redis_client.setex("trending_suggestions", 300, json.dumps(result)) + except Exception: + pass + + return result + +@router.get("/{video_id}", response_model=schemas.Video) +def read_video(video_id: str, db: Session = Depends(get_db), current_user: Optional[dict] = Depends(get_current_user_optional)): + user_id = current_user.id if current_user else None + db_video = crud_video.get_video(db, video_id=video_id, current_user_id=user_id) + if db_video is None: + raise HTTPException(status_code=404, detail="Video not found") + return db_video + + +# Processing logic migrated to Celery workers in app/tasks/video_tasks.py + +def delete_video_files(video: Video): + """Utility to delete all files (local or GCS) associated with a video.""" + urls = [ + video.video_url, + video.url_480p, + video.url_720p, + video.url_1080p, + video.url_2k, + video.url_4k, + video.thumbnail_url + ] + + current_mode = storage.mode + + for url in urls: + if not url: + continue + + s3_key = None + if current_mode == "local" and url.startswith(f"{config.BASE_URL}/static/"): + s3_key = url.replace(f"{config.BASE_URL}/static/", "") + elif current_mode == "s3" and ("amazonaws.com" in url or "cdn.monteeq.com" in url): + # Extract key after .com/ + if ".com/" in url: + s3_key = url.split(".com/")[1] + + if s3_key: + storage.delete_file(s3_key) + +@router.delete("/{video_id}") +def delete_video( + video_id: str, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + video = get_video_db(db, video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + # Check ownership or admin status + if video.owner_id != current_user.id and current_user.role != "admin": + raise HTTPException(status_code=403, detail="Not authorized to delete this video") + + # Delete physical files + delete_video_files(video) + + # Handle challenge entry counts and notifications + for entry in video.challenge_entries: + if entry.challenge: + entry.challenge.entry_count = max(0, entry.challenge.entry_count - 1) + # Notify the user + if entry.user and entry.user.email: + send_challenge_exit_email(entry.user.email, entry.user.username, entry.challenge.title) + + # Delete from DB + db.delete(video) + db.commit() + + return {"status": "success", "message": "Video deleted successfully"} + +@router.patch("/{video_id}", response_model=schemas.Video) +def update_video_metadata( + video_id: str, + video_in: schemas.VideoBase, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + video = get_video_db(db, video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + if video.owner_id != current_user.id and current_user.role != "admin": + raise HTTPException(status_code=403, detail="Not authorized") + + video.title = video_in.title + video.description = video_in.description + video.tags = video_in.tags + video.video_type = video_in.video_type + + db.commit() + db.refresh(video) + return video + + +@router.post("/upload/initiate") +async def initiate_upload( + title: str = Form(...), + description: Optional[str] = Form(None), + tags: Optional[str] = Form(None), + video_type: str = Form(...), + filename: str = Form(...), + thumbnail: Optional[UploadFile] = File(None), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + logger.info(f"Chunked Upload initiated: title='{title}', type='{video_type}', filename='{filename}', user_id={current_user.id}") + + if not current_user.is_premium: + if video_type == "flash" and current_user.flash_uploads >= FLASH_QUOTA_LIMIT: + raise HTTPException(status_code=403, detail=f"Flash quota exceeded ({FLASH_QUOTA_LIMIT} max)") + if video_type == "home" and current_user.home_uploads >= HOME_QUOTA_LIMIT: + raise HTTPException(status_code=403, detail=f"Home quota exceeded ({HOME_QUOTA_LIMIT} max)") + + import uuid + import time + import re + import unicodedata + + task_id = str(uuid.uuid4()) + + # Aggressively slugify filename + filename_base, filename_ext = os.path.splitext(filename) + safe_name = unicodedata.normalize('NFKD', filename_base).encode('ascii', 'ignore').decode('ascii') + safe_name = re.sub(r'[^\w\s-]', '', safe_name).strip().lower() + safe_name = re.sub(r'[-\s]+', '_', safe_name) + safe_filename = f"{safe_name}{filename_ext}" + + # Initial DB record + video_create_data = schemas.VideoCreate( + title=title, + description=description, + tags=tags, + video_type=video_type, + video_url="", + thumbnail_url="https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=60", + processing_key=task_id + ) + + if thumbnail: + safe_thumb_name = thumbnail.filename.replace(" ", "_") + timestamp = int(time.time()) + thumb_key = f"thumbs/custom_{timestamp}_{safe_thumb_name}" + + try: + video_create_data.thumbnail_url = storage.upload_file_obj(thumbnail.file, thumb_key) + except Exception as e: + logger.error(f"Failed to upload thumbnail to storage: {str(e)}") + + # Update quota + if video_type == "flash": + current_user.flash_uploads = (current_user.flash_uploads or 0) + 1 + else: + current_user.home_uploads = (current_user.home_uploads or 0) + 1 + + db.commit() # Save user updates + + # Create the Video database record + db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id) + # Set status as uploading initially + db_video.status = "uploading" + db.commit() + db.refresh(db_video) + + logger.info(f"Video record created in DB: id={db_video.id}, public_id={db_video.public_id}") + + # Create temp directory + backend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../")) + temp_dir = os.path.join(backend_dir, "static", "temp_uploads", task_id) + os.makedirs(temp_dir, exist_ok=True) + + return { + "upload_id": task_id, + "video_id": db_video.public_id, + "filename": safe_filename + } + + +@router.post("/upload/chunk") +async def upload_chunk( + upload_id: str = Form(...), + chunk_index: int = Form(...), + file: UploadFile = File(...), + current_user: User = Depends(get_current_user) +): + backend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../")) + temp_dir = os.path.join(backend_dir, "static", "temp_uploads", upload_id) + os.makedirs(temp_dir, exist_ok=True) + + chunk_path = os.path.join(temp_dir, f"chunk_{chunk_index}") + + logger.info(f"Saving chunk {chunk_index} for upload {upload_id}") + try: + with open(chunk_path, "wb") as f: + shutil.copyfileobj(file.file, f) + except Exception as e: + logger.error(f"Failed to save chunk {chunk_index} for upload {upload_id}: {str(e)}") + raise HTTPException(status_code=500, detail="Failed to save chunk") + + return {"status": "success", "chunk_index": chunk_index} + + +@router.get("/upload/status/{upload_id}") +async def upload_status( + upload_id: str, + current_user: User = Depends(get_current_user) +): + backend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../")) + temp_dir = os.path.join(backend_dir, "static", "temp_uploads", upload_id) + + if not os.path.exists(temp_dir): + return {"completed_chunks": []} + + completed_chunks = [] + for f in os.listdir(temp_dir): + if f.startswith("chunk_"): + try: + index = int(f.split("_")[1]) + completed_chunks.append(index) + except ValueError: + pass + + completed_chunks.sort() + return {"completed_chunks": completed_chunks} + + +@router.post("/upload/finalize") +async def finalize_upload( + upload_id: str = Form(...), + total_chunks: int = Form(...), + filename: str = Form(...), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + logger.info(f"Finalizing chunked upload {upload_id} with {total_chunks} chunks") + + backend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../")) + temp_dir = os.path.join(backend_dir, "static", "temp_uploads", upload_id) + + if not os.path.exists(temp_dir): + raise HTTPException(status_code=400, detail="Upload directory not found or session expired") + + # Check if all chunks are present + missing_chunks = [] + for i in range(total_chunks): + chunk_file = os.path.join(temp_dir, f"chunk_{i}") + if not os.path.exists(chunk_file): + missing_chunks.append(i) + + if missing_chunks: + raise HTTPException( + status_code=400, + detail=f"Missing chunks: {missing_chunks}. Please upload them first." + ) + + # Merge chunks + merged_path = os.path.join(temp_dir, filename) + try: + with open(merged_path, "wb") as outfile: + for i in range(total_chunks): + chunk_file = os.path.join(temp_dir, f"chunk_{i}") + with open(chunk_file, "rb") as infile: + shutil.copyfileobj(infile, outfile) + except Exception as e: + logger.error(f"Failed to merge chunks for upload {upload_id}: {str(e)}") + raise HTTPException(status_code=500, detail="Failed to merge chunks on server") + + # Upload to storage + source_key = f"uploads/{upload_id}/{filename}" + logger.info(f"Uploading merged video to storage: {source_key}") + + try: + with open(merged_path, "rb") as f: + storage.upload_file_obj(f, source_key) + except Exception as e: + logger.error(f"Failed to upload merged video to storage: {str(e)}") + raise HTTPException(status_code=500, detail="Failed to upload video to storage") + + # Clean up temp folder + try: + shutil.rmtree(temp_dir) + except Exception as e: + logger.warning(f"Failed to clean up temp directory {temp_dir}: {str(e)}") + + # Find the Video in database and set its status to pending + video = db.query(Video).filter(Video.processing_key == upload_id).first() + if not video: + raise HTTPException(status_code=404, detail="Video record not found") + + video.status = "pending" + db.commit() + + # Trigger Celery transcoding task + try: + from app.tasks.video_tasks import process_video_task + process_video_task.delay( + source_key, + video.video_type, + video.title, + video.id, + video.thumbnail_url != "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=60", + video.processing_key + ) + logger.info(f"Transcoding celery task enqueued for video_id={video.id}") + except Exception as e: + logger.error(f"Failed to enqueue Celery transcoding task: {str(e)}") + video.status = "failed" + db.commit() + + return {"status": "success", "video_id": video.public_id} + + +@router.post("/upload", response_model=schemas.Video) +async def upload_video( + background_tasks: BackgroundTasks, + title: str = Form(...), + description: Optional[str] = Form(None), + tags: Optional[str] = Form(None), + video_type: str = Form(...), + file: UploadFile = File(...), + thumbnail: Optional[UploadFile] = File(None), + db: Session = Depends(get_db), + current_user: dict = Depends(get_current_user) +): + logger.info(f"Upload initiated: title='{title}', type='{video_type}', user_id={current_user.id}") + + # current_user is now a User model instance, not dict + if not current_user.is_premium: + if video_type == "flash" and current_user.flash_uploads >= FLASH_QUOTA_LIMIT: + raise HTTPException(status_code=403, detail=f"Flash quota exceeded ({FLASH_QUOTA_LIMIT} max)") + if video_type == "home" and current_user.home_uploads >= HOME_QUOTA_LIMIT: + raise HTTPException(status_code=403, detail=f"Home quota exceeded ({HOME_QUOTA_LIMIT} max)") + + import uuid + import time + import re + import unicodedata + task_id = str(uuid.uuid4()) + + # Aggressively slugify filename + filename_base, filename_ext = os.path.splitext(file.filename) + safe_name = unicodedata.normalize('NFKD', filename_base).encode('ascii', 'ignore').decode('ascii') + safe_name = re.sub(r'[^\w\s-]', '', safe_name).strip().lower() + safe_name = re.sub(r'[-\s]+', '_', safe_name) + safe_filename = f"{safe_name}{filename_ext}" + + source_key = f"uploads/{task_id}/{safe_filename}" + + logger.info(f"Streaming uploaded file directly to storage: {source_key}") + try: + storage.upload_file_obj(file.file, source_key) + except Exception as e: + import traceback + error_detail = f"Storage upload failed: {str(e)}" + logger.error(f"{error_detail}\n{traceback.format_exc()}") + raise HTTPException(status_code=500, detail=error_detail) + + # Initial DB record + video_create_data = schemas.VideoCreate( + title=title, + description=description, + tags=tags, + video_type=video_type, + video_url="", + thumbnail_url="https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=60", + processing_key=task_id + ) + + if thumbnail: + safe_thumb_name = thumbnail.filename.replace(" ", "_") + timestamp = int(time.time()) + thumb_key = f"thumbs/custom_{timestamp}_{safe_thumb_name}" + + try: + video_create_data.thumbnail_url = storage.upload_file_obj(thumbnail.file, thumb_key) + except Exception as e: + logger.error(f"Failed to upload thumbnail to storage: {str(e)}") + + # Update quota + if video_type == "flash": + current_user.flash_uploads = (current_user.flash_uploads or 0) + 1 + else: + current_user.home_uploads = (current_user.home_uploads or 0) + 1 + + db.commit() # Save user updates + + db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id) + logger.info(f"Video record created in DB: id={db_video.id}") + + try: + from app.tasks.video_tasks import process_video_task + process_video_task.delay( + source_key, + video_type, + title, + db_video.id, + thumbnail is not None, + db_video.processing_key + ) + logger.info(f"Celery task enqueued for video_id={db_video.id}") + except Exception as e: + logger.error(f"Failed to enqueue Celery task: {str(e)}") + # We still return the video, but flag it as failed immediately or show a specific message + db_video.status = "failed" + db.commit() + raise HTTPException(status_code=500, detail="Video enqueued for processing but local queue is unreachable.") + + return db_video + + +@router.post("/{video_id}/reupload", response_model=schemas.Video) +async def reupload_video( + video_id: str, + background_tasks: BackgroundTasks, + file: UploadFile = File(...), + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + video = get_video_db(db, video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + if video.owner_id != current_user.id and current_user.role != "admin": + raise HTTPException(status_code=403, detail="Not authorized") + + if video.status != "failed": + raise HTTPException(status_code=400, detail="Only failed videos can be reuploaded") + + + import uuid + task_id = str(uuid.uuid4()) + safe_filename = file.filename.replace(" ", "_") + source_key = f"uploads/{task_id}/{safe_filename}" + + try: + storage.upload_file_obj(file.file, source_key) + except Exception as e: + raise HTTPException(status_code=500, detail="Failed to reupload video file to storage") + + + video.processing_key = task_id + video.status = "pending" + video.failed_at = None + db.commit() + + from app.tasks.video_tasks import process_video_task + process_video_task.delay( + source_key, + video.video_type, + video.title, + video.id, + False, # thumbnail_provided = False + video.processing_key + ) + + return video + +@router.get("/status/{key}") +async def get_processing_status(key: str, db: Session = Depends(get_db)): + logger.info(f"[STATUS] Checking status for key: {key}") + + # 1. Try to get status from Redis directly (Shared with Rust service) + try: + import json + status_data_raw = redis_client.get(f"task:status:{key}") + if status_data_raw: + status_data = json.loads(status_data_raw) + logger.info(f"[STATUS] Redis found: {status_data}") + + # Map Rust status to Frontend expectations if needed + # Rust statuses: "queued", "processing", "completed", "error" + rust_status = status_data.get("status") + if rust_status == "completed": + # Verify Phase 2 in DB + video = db.query(Video).filter(Video.processing_key == key).first() + if video and video.status == "approved": + return {"status": "completed", "progress": 100, "message": "Ready"} + return {"status": "processing", "progress": 99, "message": "Finalizing..."} + + return { + "status": "processing" if rust_status in ["queued", "processing"] else rust_status, + "progress": status_data.get("progress", 0), + "message": status_data.get("message", "") + } + except Exception as e: + logger.warning(f"[STATUS] Redis error: {e}") + + # 2. Fallback: Get persistent status from Database + video = db.query(Video).filter(Video.processing_key == key).first() + if video: + if video.status == "approved": + return {"status": "completed", "progress": 100, "message": "Ready"} + if video.status == "failed": + return {"status": "error", "progress": 0, "message": "Failed"} + + return { + "status": "processing", + "progress": 50, + "message": video.processing_message or "Processing..." + } + + return {"status": "unknown"} + + +@router.post("/{video_id}/view") +def view_video( + video_id: str, + request: Request, + db: Session = Depends(get_db), + current_user: Optional[dict] = Depends(get_current_user_optional) +): + # Bot detection + user_agent = request.headers.get("User-Agent", "").lower() + bot_keywords = ["bot", "crawler", "spider", "google", "bing", "yahoo", "slurp", "headless", "phantom"] + if any(keyword in user_agent for keyword in bot_keywords): + return {"status": "success", "message": "Bot detected, view not counted"} + + video = crud_video.get_video(db, video_id=video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + if video.status != "approved": + # Silently skip view increment for pending/failed videos + # but return success to avoid frontend errors + return {"status": "success", "views": video.views, "message": "View not counted for non-approved video"} + + user_id = current_user.id if current_user else None + updated_video = crud_video.increment_view(db, user_id=user_id, video_id=video.id) + return {"status": "success", "views": updated_video.views if updated_video else 0} + +@router.post("/{video_id}/comments", response_model=schemas.Comment) +def create_comment( + video_id: str, + comment: schemas.CommentCreate, + background_tasks: BackgroundTasks, + request: Request, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + # Rate Limit: 5 comments per minute per IP + from app.core import security + if not security.check_rate_limit(f"ratelimit:comment:{request.client.host}", 5, 60): + raise HTTPException(status_code=429, detail="You are commenting too fast. Please wait.") + + video = crud_video.get_video(db, video_id=video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + if video.status != "approved": + raise HTTPException(status_code=403, detail="Comments are disabled for videos still in processing or failed state") + + db_comment = crud_video.create_comment(db, comment=comment, user_id=current_user.id, video_id=video.id) + + # Background side effects + background_tasks.add_task(handle_comment_background, current_user.id, video_id=video.id) + + return db_comment + +@router.get("/{video_id}/comments", response_model=List[schemas.Comment]) +def read_comments(video_id: str, db: Session = Depends(get_db), current_user: Optional[User] = Depends(get_current_user_optional)): + video = crud_video.get_video(db, video_id=video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + return crud_video.get_comments(db, video_id=video.id, current_user_id=current_user.id if current_user else None) + +def handle_like_background(user_id: int, video_id: int): + """Background task to handle side effects of a video like.""" + db = SessionLocal() + try: + crud_video.handle_like_side_effects(db, user_id, video_id=video_id) + finally: + db.close() + +def handle_comment_background(user_id: int, video_id: Optional[int] = None, post_id: Optional[int] = None): + """Background task to handle side effects of a comment.""" + db = SessionLocal() + try: + crud_video.handle_comment_side_effects(db, user_id, video_id=video_id, post_id=post_id) + finally: + db.close() + +@router.post("/{video_id}/like") +def like_video( + video_id: str, + background_tasks: BackgroundTasks, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + video = crud_video.get_video(db, video_id=video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + if video.status != "approved": + raise HTTPException(status_code=403, detail="Likes are disabled for videos still in processing or failed state") + + is_liked = crud_video.toggle_like(db, user_id=current_user.id, video_id=video.id) + + if is_liked: + # Perform notifications and score updates in background + background_tasks.add_task(handle_like_background, current_user.id, video.id) + + from app.models.models import Like + likes_count = db.query(func.count(Like.video_id)).filter(Like.video_id == video.id).scalar() or 0 + + return {"status": "success", "liked": is_liked, "likes_count": likes_count} + + +@router.post("/{video_id}/share") +def share_video( + video_id: str, + db: Session = Depends(get_db) +): + video = crud_video.get_video(db, video_id=video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + crud_video.increment_share(db, video_id=video.id) + return {"status": "success"} + +@router.put("/{video_id}/comments/{comment_id}", response_model=schemas.Comment) +def update_comment( + video_id: str, + comment_id: int, + comment_in: schemas.CommentBase, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + # Verify video exists + video = crud_video.get_video(db, video_id=video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + result = crud_video.update_comment(db, comment_id=comment_id, user_id=current_user.id, content=comment_in.content) + if result is None: + raise HTTPException(status_code=404, detail="Comment not found") + if result is False: + raise HTTPException(status_code=403, detail="Not authorized to edit this comment") + return result + +@router.delete("/{video_id}/comments/{comment_id}") +def delete_comment( + video_id: str, + comment_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user) +): + # Verify video exists + video = crud_video.get_video(db, video_id=video_id) + if not video: + raise HTTPException(status_code=404, detail="Video not found") + + result = crud_video.delete_comment(db, comment_id=comment_id, user_id=current_user.id) + if result is None: + raise HTTPException(status_code=404, detail="Comment not found") + if result is False: + raise HTTPException(status_code=403, detail="Not authorized to delete this comment") + return {"status": "success", "message": "Comment deleted successfully"} diff --git a/app/api/v1/endpoints/watch_later.py b/app/api/v1/endpoints/watch_later.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c1007b12f39a5876b1b2f2db22f83bf49ea2ef --- /dev/null +++ b/app/api/v1/endpoints/watch_later.py @@ -0,0 +1,107 @@ +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select +from sqlalchemy import func, delete +from sqlalchemy.orm import selectinload +from datetime import datetime, timedelta, timezone + +from app.db.async_session import get_async_db +from app.schemas import library as schemas +from app.models.library import LibraryWatchLater +from app.models.models import Video +from app.core.async_dependencies import get_async_current_user + +router = APIRouter() + +@router.get("/", response_model=schemas.WatchLaterResponse) +async def get_watch_later( + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + query = select(LibraryWatchLater).options( + selectinload(LibraryWatchLater.video).selectinload(Video.owner) + ).filter(LibraryWatchLater.user_id == current_user.id).order_by(LibraryWatchLater.saved_at.desc()) + result = await db.execute(query) + items = result.scalars().all() + + # Stats + total_videos = len(items) + total_runtime = sum([item.video.duration for item in items if item.video.duration]) + + now = datetime.now(timezone.utc) + week_ago = now - timedelta(days=7) + + def is_newer_than_week(saved_at): + if saved_at is None: + return False + if saved_at.tzinfo is not None: + return saved_at >= week_ago + return saved_at >= week_ago.replace(tzinfo=None) + + new_this_week = sum([1 for item in items if is_newer_than_week(item.saved_at)]) + + return { + "items": items, + "stats": { + "total_videos": total_videos, + "total_runtime_seconds": total_runtime, + "new_this_week": new_this_week + } + } + +async def get_video_db_async(db: AsyncSession, video_id: str) -> Video: + if isinstance(video_id, str) and not video_id.isdigit(): + result = await db.execute(select(Video).filter(Video.public_id == video_id)) + else: + result = await db.execute(select(Video).filter(Video.id == int(video_id))) + video = result.scalar_one_or_none() + if not video: + raise HTTPException(status_code=404, detail="Video not found") + return video + +@router.post("/{video_id}") +async def add_to_watch_later( + video_id: str, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + video = await get_video_db_async(db, video_id) + # Check if exists + result = await db.execute(select(LibraryWatchLater).filter( + LibraryWatchLater.user_id == current_user.id, + LibraryWatchLater.video_id == video.id + )) + + if result.scalar_one_or_none(): + return {"status": "already_exists"} + + new_item = LibraryWatchLater(user_id=current_user.id, video_id=video.id) + + db.add(new_item) + await db.commit() + return {"status": "success"} + +@router.delete("/{video_id}") +async def remove_from_watch_later( + video_id: str, + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + video = await get_video_db_async(db, video_id) + await db.execute(delete(LibraryWatchLater).filter( + LibraryWatchLater.user_id == current_user.id, + LibraryWatchLater.video_id == video.id + )) + + await db.commit() + return {"status": "success"} + +@router.delete("/") +async def clear_watch_later( + db: AsyncSession = Depends(get_async_db), + current_user = Depends(get_async_current_user) +): + await db.execute(delete(LibraryWatchLater).filter(LibraryWatchLater.user_id == current_user.id)) + + await db.commit() + return {"status": "success"} diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/core/async_dependencies.py b/app/core/async_dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..a7799ce33e4cf6a5621abb59faf05c896d1b2363 --- /dev/null +++ b/app/core/async_dependencies.py @@ -0,0 +1,42 @@ +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select + +from app.core.config import SECRET_KEY, ALGORITHM +from app.db.async_session import get_async_db +from app.models.models import User + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + +async def get_async_current_user( + db: AsyncSession = Depends(get_async_db), + token: str = Depends(oauth2_scheme) +): + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get("sub") + if username is None: + raise credentials_exception + except JWTError: + raise credentials_exception + + result = await db.execute(select(User).filter(User.username == username)) + user = result.scalar_one_or_none() + + if not user: + raise credentials_exception + + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is deactivated" + ) + + return user diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a52057cffe8a2191a4b3ee76e6a17be95ac81bef --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,52 @@ +import os +from dotenv import load_dotenv + +# Load .env file from the backend directory +env_path = os.path.join(os.path.dirname(__file__), "..", "..", ".env") +load_dotenv(env_path) + +SECRET_KEY = os.getenv("SECRET_KEY", "SUPER_SECRET_KEY_CHANGE_ME") +ALGORITHM = os.getenv("ALGORITHM", "HS256") +ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "43200")) + +GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID", "") +BASE_URL = os.getenv("BASE_URL") +RUST_SERVICE_URL = os.getenv("RUST_SERVICE_URL") +FRONTEND_URL = os.getenv("FRONTEND_URL", "") +STATIC_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "static") + +# Database Configuration +DATABASE_URL = os.getenv("DATABASE_URL") + +# Quota Limits +FLASH_QUOTA_LIMIT = 50 +HOME_QUOTA_LIMIT = 20 + +# Storage Configuration +STORAGE_MODE = os.getenv("STORAGE_MODE", "s3") # 'local' or 's3' +AWS_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY", os.getenv("AWS_ACCESS_KEY_ID", "")) +AWS_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_KEY", os.getenv("AWS_SECRET_ACCESS_KEY", "")) +AWS_STORAGE_BUCKET_NAME = os.getenv("S3_BUCKET_NAME", os.getenv("AWS_STORAGE_BUCKET_NAME", "monteeq")) +AWS_S3_REGION_NAME = os.getenv("S3_REGION", os.getenv("AWS_S3_REGION_NAME", "eu-north-1")) +S3_ENDPOINT = os.getenv("S3_ENDPOINT", None) +AWS_S3_USE_ACCELERATE = os.getenv("AWS_S3_USE_ACCELERATE", "false").lower() == "true" +AWS_CLOUDFRONT_DOMAIN = os.getenv("AWS_CLOUDFRONT_DOMAIN", "") # Remove default to avoid broken URLs + +PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "") +# STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "") +# STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET", "") +STRIPE_SECRET_KEY = "" +STRIPE_WEBHOOK_SECRET = "" + + +# Email / SMTP Configuration +SMTP_HOST = os.getenv("SMTP_HOST", "") +SMTP_PORT = int(os.getenv("SMTP_PORT", "587")) +SMTP_USER = os.getenv("SMTP_USER", "") +SMTP_PASS = os.getenv("SMTP_PASS", "") +SMTP_FROM = os.getenv("SMTP_FROM", "") +SMTP_FROM_NAME = os.getenv("SMTP_FROM_NAME", "Monteeq") + +# Redis Configuration (Live Cloud) +REDIS_URL = os.getenv("REDIS_URL") + diff --git a/app/core/dependencies.py b/app/core/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..3be2550118316fe4911ab3ca0e7d8a43ef22a30a --- /dev/null +++ b/app/core/dependencies.py @@ -0,0 +1,91 @@ +from datetime import datetime, timezone +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from sqlalchemy.orm import Session + +from app.core.config import SECRET_KEY, ALGORITHM +from app.db.session import get_db +from app.models.models import User +from app.schemas import schemas + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") +oauth2_scheme_optional = OAuth2PasswordBearer(tokenUrl="token", auto_error=False) + + +def _expire_premium_if_needed(user: User, db: Session) -> None: + """Downgrade premium when subscription has expired.""" + if user.is_premium and user.premium_expires_at: + if user.premium_expires_at < datetime.now(timezone.utc): + user.is_premium = False + db.commit() + + +async def get_current_user( + db: Session = Depends(get_db), + token: str = Depends(oauth2_scheme) +): + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get("sub") + if username is None: + raise credentials_exception + except JWTError: + raise credentials_exception + + # Fetch user from DB + user = db.query(User).filter(User.username == username).first() + if not user: + raise credentials_exception + + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is deactivated" + ) + + _expire_premium_if_needed(user, db) + return user + +async def get_current_user_optional( + db: Session = Depends(get_db), + token: str = Depends(oauth2_scheme_optional) +): + if not token: + return None + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get("sub") + if username is None: + return None + except JWTError: + return None + + # Fetch user from DB + user = db.query(User).filter(User.username == username).first() + + if user: + _expire_premium_if_needed(user, db) + + return user + + +def role_checker(allowed_roles: list): + def checker(current_user: dict = Depends(get_current_user)): + # Handle dict or model + role = current_user.get("role") if isinstance(current_user, dict) else getattr(current_user, "role", None) + if role not in allowed_roles: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Operation not permitted" + ) + return current_user + return checker + +admin_only = role_checker(["admin"]) + diff --git a/app/core/error_handlers.py b/app/core/error_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..44a7bf0aee8aa08154035e57854489b51c6fc8bd --- /dev/null +++ b/app/core/error_handlers.py @@ -0,0 +1,147 @@ +""" +Monteeq Global Exception Handlers +==================================== +Register all handlers with `register_exception_handlers(app)` inside main.py. + +Every error response follows a consistent shape: +{ + "error_code": "SNAKE_CASE_CODE", + "detail": "Human-readable message", + "status_code": 4xx | 5xx, + "trace_id": "uuid-for-server-logs", # only on 5xx + "fields": [...] # only on validation errors +} +""" +from __future__ import annotations + +import logging +import traceback +import uuid + +from fastapi import FastAPI, Request, status +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException + +from app.core.exceptions import MonteeqException + +logger = logging.getLogger("monteeq") + + +# ── Helper ──────────────────────────────────────────────────────────────────── + +def _json(status_code: int, body: dict) -> JSONResponse: + return JSONResponse(status_code=status_code, content=body) + + +def _trace_id() -> str: + return str(uuid.uuid4()) + + +# ── Handlers ───────────────────────────────────────────────────────────────── + +async def monteeq_exception_handler( + request: Request, exc: MonteeqException +) -> JSONResponse: + """Handle all custom Monteeq exceptions.""" + logger.warning( + "MonteeqException [%s] %s — %s %s", + exc.status_code, + exc.error_code, + request.method, + request.url.path, + ) + return _json(exc.status_code, exc.to_dict()) + + +async def http_exception_handler( + request: Request, exc: StarletteHTTPException +) -> JSONResponse: + """Normalise FastAPI / Starlette HTTPExceptions into the standard shape.""" + # Map common status codes to Monteeq error codes + code_map = { + 400: "BAD_REQUEST", + 401: "UNAUTHORIZED", + 403: "FORBIDDEN", + 404: "NOT_FOUND", + 405: "METHOD_NOT_ALLOWED", + 409: "CONFLICT", + 422: "UNPROCESSABLE", + 429: "RATE_LIMITED", + 500: "INTERNAL_SERVER_ERROR", + 503: "SERVICE_UNAVAILABLE", + } + error_code = code_map.get(exc.status_code, "HTTP_ERROR") + + body: dict = { + "error_code": error_code, + "detail": exc.detail or "An error occurred.", + "status_code": exc.status_code, + } + return _json(exc.status_code, body) + + +async def validation_exception_handler( + request: Request, exc: RequestValidationError +) -> JSONResponse: + """Pydantic / FastAPI request-body validation errors → readable field list.""" + fields = [] + for error in exc.errors(): + loc = " → ".join(str(l) for l in error["loc"] if l != "body") + fields.append( + { + "field": loc, + "message": error["msg"], + "type": error["type"], + } + ) + + logger.info( + "ValidationError on %s %s: %d field(s)", + request.method, + request.url.path, + len(fields), + ) + + return _json( + status.HTTP_422_UNPROCESSABLE_ENTITY, + { + "error_code": "VALIDATION_ERROR", + "detail": "One or more fields failed validation.", + "status_code": 422, + "fields": fields, + }, + ) + + +async def unhandled_exception_handler( + request: Request, exc: Exception +) -> JSONResponse: + """Catch-all for any unhandled exception — log full traceback, return 500.""" + trace_id = _trace_id() + logger.error( + "Unhandled exception [trace=%s] on %s %s\n%s", + trace_id, + request.method, + request.url.path, + traceback.format_exc(), + ) + return _json( + status.HTTP_500_INTERNAL_SERVER_ERROR, + { + "error_code": "INTERNAL_SERVER_ERROR", + "detail": "An unexpected server error occurred. Our team has been notified.", + "status_code": 500, + "trace_id": trace_id, + }, + ) + + +# ── Registration ────────────────────────────────────────────────────────────── + +def register_exception_handlers(app: FastAPI) -> None: + """Call this once in main.py to attach all handlers to the app.""" + app.add_exception_handler(MonteeqException, monteeq_exception_handler) + app.add_exception_handler(StarletteHTTPException, http_exception_handler) + app.add_exception_handler(RequestValidationError, validation_exception_handler) + app.add_exception_handler(Exception, unhandled_exception_handler) diff --git a/app/core/exceptions.py b/app/core/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1272ad0a190ea60fbdedbd0092b0fe2b237311 --- /dev/null +++ b/app/core/exceptions.py @@ -0,0 +1,143 @@ +""" +Monteeq Custom Exception Hierarchy +=================================== +All application exceptions derive from MonteeqException so that +the global exception handler can catch and format them uniformly. + +Usage: + raise NotFoundError("Video not found", error_code="VIDEO_NOT_FOUND") + raise ForbiddenError() # sensible defaults + raise VideoProcessingError("Transcoding failed") +""" +from __future__ import annotations + +from typing import Optional + + +class MonteeqException(Exception): + """Base exception for all Monteeq application errors.""" + + status_code: int = 500 + default_detail: str = "An unexpected error occurred." + default_error_code: str = "INTERNAL_SERVER_ERROR" + + def __init__( + self, + detail: Optional[str] = None, + error_code: Optional[str] = None, + extra: Optional[dict] = None, + ): + self.detail = detail or self.default_detail + self.error_code = error_code or self.default_error_code + self.extra = extra or {} + super().__init__(self.detail) + + def to_dict(self) -> dict: + payload: dict = { + "error_code": self.error_code, + "detail": self.detail, + "status_code": self.status_code, + } + if self.extra: + payload["extra"] = self.extra + return payload + + +# ── 4xx Client Errors ──────────────────────────────────────────────────────── + +class BadRequestError(MonteeqException): + status_code = 400 + default_detail = "Bad request." + default_error_code = "BAD_REQUEST" + + +class UnauthorizedError(MonteeqException): + status_code = 401 + default_detail = "Authentication required." + default_error_code = "UNAUTHORIZED" + + +class ForbiddenError(MonteeqException): + status_code = 403 + default_detail = "You do not have permission to perform this action." + default_error_code = "FORBIDDEN" + + +class NotFoundError(MonteeqException): + status_code = 404 + default_detail = "The requested resource was not found." + default_error_code = "NOT_FOUND" + + +class ConflictError(MonteeqException): + status_code = 409 + default_detail = "A conflict occurred with the current state of the resource." + default_error_code = "CONFLICT" + + +class UnprocessableError(MonteeqException): + status_code = 422 + default_detail = "The request could not be processed." + default_error_code = "UNPROCESSABLE" + + +class RateLimitError(MonteeqException): + status_code = 429 + default_detail = "Too many requests. Please slow down." + default_error_code = "RATE_LIMITED" + + +# ── 5xx Server Errors ──────────────────────────────────────────────────────── + +class ServerError(MonteeqException): + status_code = 500 + default_detail = "An internal server error occurred." + default_error_code = "INTERNAL_SERVER_ERROR" + + +class ServiceUnavailableError(MonteeqException): + status_code = 503 + default_detail = "The service is temporarily unavailable." + default_error_code = "SERVICE_UNAVAILABLE" + + +# ── Domain-Specific Errors ─────────────────────────────────────────────────── + +class VideoNotFoundError(NotFoundError): + default_detail = "Video not found." + default_error_code = "VIDEO_NOT_FOUND" + + +class VideoProcessingError(ServerError): + default_detail = "Video processing failed." + default_error_code = "VIDEO_PROCESSING_ERROR" + + +class StorageError(ServerError): + default_detail = "A storage operation failed." + default_error_code = "STORAGE_ERROR" + + +class PaymentError(BadRequestError): + default_detail = "Payment processing failed." + default_error_code = "PAYMENT_ERROR" + + +class UserNotFoundError(NotFoundError): + default_detail = "User not found." + default_error_code = "USER_NOT_FOUND" + + +class AccountDeactivatedError(ForbiddenError): + default_detail = "This account has been deactivated." + default_error_code = "ACCOUNT_DEACTIVATED" + + +class InsufficientBalanceError(BadRequestError): + default_detail = "Insufficient wallet balance." + default_error_code = "INSUFFICIENT_BALANCE" + + +class ChallengeError(BadRequestError): + default_detail = "Challenge operation failed." + default_error_code = "CHALLENGE_ERROR" diff --git a/app/core/redis.py b/app/core/redis.py new file mode 100644 index 0000000000000000000000000000000000000000..cff9a5b7d8a3e3b079fd31456517b828d1d3a8ea --- /dev/null +++ b/app/core/redis.py @@ -0,0 +1,79 @@ +import redis +import logging +from app.core.config import REDIS_URL + +logger = logging.getLogger(__name__) + +class RedisManager: + """ + Centralized Redis connection manager using a Singleton pattern. + Provides a thread-safe StrictRedis client with automatic reconnection and basic health checks. + """ + _instance = None + _client = None + last_error = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super(RedisManager, cls).__new__(cls) + return cls._instance + + @property + def client(self): + if self._client is None: + self.connect() + return self._client + + def connect(self): + """Initializes the Redis client and validates the connection.""" + try: + # Use connection pooling for efficiency and stability + pool = redis.ConnectionPool.from_url( + REDIS_URL, + decode_responses=True, + socket_timeout=5, + socket_connect_timeout=5, + retry_on_timeout=True, + max_connections=50 + ) + self._client = redis.StrictRedis(connection_pool=pool) + + # Simple health check to ensure Redis is responsive + self._client.ping() + self.last_error = None + logger.info(f"Successfully connected to Redis Cloud at {REDIS_URL[:20]}...") + except Exception as e: + self.last_error = f"{type(e).__name__}: {str(e)}" + logger.error(f"FATAL: Could not connect to Redis Cloud. Error: {e}") + # We don't raise here to allow the app to start, + # but specific features requiring Redis will fail gracefully later. + self._client = None + + def get_client(self): + """Returns the active Redis client instance.""" + return self.client + +class RedisClientProxy: + """ + A lazy proxy that forwards attributes to the active Redis client. + Allows retrying connection dynamically if it was previously disconnected. + """ + @property + def _real_client(self): + client = redis_manager.client + if client is None: + raise redis.ConnectionError(f"Redis client is not connected. Last error: {redis_manager.last_error}") + return client + + def __getattr__(self, name): + return getattr(self._real_client, name) + + def __repr__(self): + try: + return repr(self._real_client) + except Exception: + return f"" + +# Export a single instance for use across the application +redis_manager = RedisManager() +redis_client = RedisClientProxy() diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0342a74723d9383250c45b1c4b7ec0ba18527b --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,78 @@ +from datetime import datetime, timedelta +from typing import Optional +from jose import JWTError, jwt +from passlib.context import CryptContext +from app.core.config import SECRET_KEY, ALGORITHM + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +import hashlib + +def verify_password(plain_password, hashed_password): + try: + if pwd_context.verify(plain_password, hashed_password): + return True + except ValueError: + # Password too long for bcrypt, try pre-hashed version + pass + + # Try verifying with pre-hashed password (for new users or long passwords) + # We use SHA256 hexdigest as the input to bcrypt, which is always 64 chars + pre_hashed = hashlib.sha256(plain_password.encode()).hexdigest() + return pwd_context.verify(pre_hashed, hashed_password) + +def get_password_hash(password): + # Always pre-hash new passwords to support arbitrary length + pre_hashed = hashlib.sha256(password.encode()).hexdigest() + return pwd_context.hash(pre_hashed) + +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): + to_encode = data.copy() + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(minutes=15) + to_encode.update({"exp": expire}) + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + return encoded_jwt + +def is_bot(request) -> bool: + """ + Heuristic-based bot detection. + Checks User-Agent, missing standard headers, and known headless browser patterns. + """ + user_agent = request.headers.get("User-Agent", "").lower() + + # 1. Extensive User-Agent Blacklist + bot_keywords = [ + "bot", "crawler", "spider", "slurp", "headless", + "phantom", "selenium", "puppeteer", "playwright", "python", "curl", "wget", + "postman", "insomnia", "scrapy", "ahrefs", "semrush", "majestic", + "dotbot", "rogerbot", "exabot", "gigabot", "yandex", "baiduspider", "petalbot" + ] + + # Legit crawlers to allowlist + legit_crawlers = ["googlebot", "bingbot", "google-site-verification", "adsbot-google", "bingpreview"] + + if any(keyword in user_agent for keyword in bot_keywords): + # Double check if it's a legit one + if any(legit in user_agent for legit in legit_crawlers): + return False + return True + + # 2. Heuristic check: removed overly aggressive header check for real users. + # We rely on User-Agent blacklist and other layers for now. + return False + + # 3. Automation-specific headers + if request.headers.get("X-Selenium-Driver") or request.headers.get("X-Puppeteer-Session"): + return True + + return False + +def check_rate_limit(key: str, limit: int, period: int) -> bool: + """ + Rate limiting has been disabled per user request. + Always returns True. + """ + return True diff --git a/app/core/storage.py b/app/core/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..203ab30f9e8686e2bd42a5500fc295a7f316239f --- /dev/null +++ b/app/core/storage.py @@ -0,0 +1,261 @@ +import os +import logging +import time +from typing import Optional +import shutil +import boto3 +from botocore.exceptions import ClientError +from sqlalchemy.orm import Session + +from app.core import config +from app.db.session import SessionLocal +from app.models.models import Setting + +logger = logging.getLogger(__name__) + +class Storage: + def __init__(self): + self._mode: Optional[str] = None + self._mode_cache_time: float = 0 + self._cache_ttl: int = 60 # Cache DB mode for 60 seconds + + self.s3_client = None + if config.AWS_ACCESS_KEY_ID: + self._init_s3_client() + + def _init_s3_client(self): + try: + from botocore.config import Config + + is_hf_bucket = config.S3_ENDPOINT and "s3.hf.co" in config.S3_ENDPOINT + + if is_hf_bucket: + # HF Storage Buckets require path-style addressing and us-east-1 region + s3_opts = {'region_name': 'us-east-1', 'addressing_style': 'path'} + logger.info("Using Hugging Face Storage Bucket endpoint") + else: + s3_opts = {'region_name': config.AWS_S3_REGION_NAME} + if config.AWS_S3_USE_ACCELERATE: + s3_opts['use_accelerate_endpoint'] = True + logger.info("Enabling S3 Transfer Acceleration") + + s3_config = Config(s3=s3_opts) + self.s3_client = boto3.client( + 's3', + aws_access_key_id=config.AWS_ACCESS_KEY_ID, + aws_secret_access_key=config.AWS_SECRET_ACCESS_KEY, + endpoint_url=config.S3_ENDPOINT, + config=s3_config + ) + logger.info("Successfully initialized S3-compatible client") + except Exception as e: + logger.error(f"Failed to initialize S3 client: {e}", exc_info=True) + + @property + def mode(self) -> str: + """ + Dynamically resolves the storage mode from the database with a TTL cache. + Falls back to config.STORAGE_MODE if not set in DB. + """ + current_time = time.time() + if self._mode and (current_time - self._mode_cache_time) < self._cache_ttl: + return self._mode + + db = SessionLocal() + try: + setting = db.query(Setting).filter(Setting.key == "storage_mode").first() + if setting and setting.value: + self._mode = setting.value + else: + self._mode = config.STORAGE_MODE + self._mode_cache_time = current_time + except Exception as e: + logger.error(f"Error fetching storage_mode from DB: {e}", exc_info=True) + self._mode = config.STORAGE_MODE + finally: + db.close() + + return self._mode + + def upload_file(self, local_path: str, s3_key: str) -> str: + """ + Uploads a file to the active storage provider and returns its URL. + """ + current_mode = self.mode + + if current_mode == "local": + return self._upload_local(local_path, s3_key) + else: + return self._upload_s3(local_path, s3_key) + + def _upload_local(self, local_path: str, s3_key: str) -> str: + dest_path = os.path.join(config.STATIC_DIR, s3_key) + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + shutil.copy2(local_path, dest_path) + url_key = s3_key.replace(os.sep, "/") + return f"{config.BASE_URL}/static/{url_key}" + + def _upload_s3(self, local_path: str, s3_key: str) -> str: + if not self.s3_client: + raise ValueError("AWS S3 client is not initialized.") + try: + # S3 upload_file handles chunking and multi-part automatically + self.s3_client.upload_file( + local_path, + config.AWS_STORAGE_BUCKET_NAME, + s3_key + ) + return self.get_url(s3_key, mode="s3") + except Exception as e: + logger.error(f"S3 Upload failed for {s3_key}: {e}", exc_info=True) + raise + + def upload_file_obj(self, file_obj, s3_key: str) -> str: + """ + Uploads a file-like object directly to storage (avoids local disk). + """ + current_mode = self.mode + + if current_mode == "local": + dest_path = os.path.join(config.STATIC_DIR, s3_key) + os.makedirs(os.path.dirname(dest_path), exist_ok=True) + with open(dest_path, "wb") as buffer: + shutil.copyfileobj(file_obj, buffer) + url_key = s3_key.replace(os.sep, "/") + return f"{config.BASE_URL}/static/{url_key}" + else: + if not self.s3_client: + raise ValueError("AWS S3 client is not initialized.") + try: + # Detect content type from the key extension + ext = os.path.splitext(s3_key)[1].lower() + content_type_map = { + ".mp4": "video/mp4", + ".mov": "video/quicktime", + ".avi": "video/x-msvideo", + ".mkv": "video/x-matroska", + ".webm": "video/webm", + ".m3u8": "application/x-mpegURL", + ".ts": "video/MP2T", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + } + content_type = content_type_map.get(ext, "application/octet-stream") + + from boto3.s3.transfer import TransferConfig + config_s3 = TransferConfig( + multipart_threshold=1024 * 25, # 25MB + max_concurrency=10, + multipart_chunksize=1024 * 25, # 25MB + use_threads=True + ) + + self.s3_client.upload_fileobj( + file_obj, + config.AWS_STORAGE_BUCKET_NAME, + s3_key, + ExtraArgs={ + 'ContentType': content_type + }, + Config=config_s3 + ) + return self.get_url(s3_key, mode="s3") + except Exception as e: + logger.error(f"S3 Object Upload failed for {s3_key}: {e}", exc_info=True) + raise + + def get_url(self, s3_key: str, mode: Optional[str] = None) -> str: + """ + Returns the public URL for a given key. + Uses CloudFront if configured, otherwise falls back to the endpoint or S3. + """ + current_mode = mode or self.mode + url_key = s3_key.replace(os.sep, "/") + + if current_mode == "local": + return f"{config.BASE_URL}/static/{url_key}" + + # CloudFront takes highest priority (fastest CDN delivery) + if config.AWS_CLOUDFRONT_DOMAIN: + return f"https://{config.AWS_CLOUDFRONT_DOMAIN}/{url_key}" + + # Hugging Face Storage Bucket — path-style URL + if config.S3_ENDPOINT and "s3.hf.co" in config.S3_ENDPOINT: + return f"{config.S3_ENDPOINT.rstrip('/')}/{config.AWS_STORAGE_BUCKET_NAME}/{url_key}" + + # Generic S3-compatible endpoint (e.g. Backblaze, MinIO) + if config.S3_ENDPOINT: + endpoint_host = config.S3_ENDPOINT.replace("https://", "").replace("http://", "") + return f"https://{config.AWS_STORAGE_BUCKET_NAME}.{endpoint_host}/{url_key}" + + # Fallback to direct AWS S3 + return f"https://{config.AWS_STORAGE_BUCKET_NAME}.s3.{config.AWS_S3_REGION_NAME}.amazonaws.com/{url_key}" + + def delete_file(self, s3_key: str) -> None: + """ + Deletes a file from storage. + """ + current_mode = self.mode + + if current_mode == "local": + local_path = os.path.join(config.STATIC_DIR, s3_key.replace("/", os.sep)) + if os.path.exists(local_path): + try: + os.remove(local_path) + logger.info(f"Deleted local file: {local_path}") + except Exception as e: + logger.error(f"Failed to delete local file {local_path}: {e}", exc_info=True) + else: + if not self.s3_client: + logger.error("Cannot delete from S3: Client not initialized.") + return + try: + self.s3_client.delete_object( + Bucket=config.AWS_STORAGE_BUCKET_NAME, + Key=s3_key + ) + logger.info(f"Deleted S3 object: {s3_key}") + except Exception as e: + logger.error(f"Failed to delete S3 object {s3_key}: {e}", exc_info=True) + def delete_prefix(self, prefix: str) -> None: + """ + Deletes all objects with the given prefix (folder deletion). + """ + current_mode = self.mode + + if current_mode == "local": + local_dir = os.path.join(config.STATIC_DIR, prefix.replace("/", os.sep)) + if os.path.exists(local_dir) and os.path.isdir(local_dir): + try: + shutil.rmtree(local_dir) + logger.info(f"Deleted local directory: {local_dir}") + except Exception as e: + logger.error(f"Failed to delete local directory {local_dir}: {e}", exc_info=True) + else: + if not self.s3_client: + logger.error("Cannot delete from S3: Client not initialized.") + return + try: + # Paginate through objects with prefix and delete them + paginator = self.s3_client.get_paginator('list_objects_v2') + pages = paginator.paginate(Bucket=config.AWS_STORAGE_BUCKET_NAME, Prefix=prefix) + + delete_us = dict(Objects=[]) + for item in pages.search('Contents'): + if item: + delete_us['Objects'].append(dict(Key=item['Key'])) + + # S3 delete_objects has a limit of 1000 per call + if len(delete_us['Objects']) >= 1000: + self.s3_client.delete_objects(Bucket=config.AWS_STORAGE_BUCKET_NAME, Delete=delete_us) + delete_us = dict(Objects=[]) + + if len(delete_us['Objects']): + self.s3_client.delete_objects(Bucket=config.AWS_STORAGE_BUCKET_NAME, Delete=delete_us) + + logger.info(f"Deleted S3 prefix: {prefix}") + except Exception as e: + logger.error(f"Failed to delete S3 prefix {prefix}: {e}", exc_info=True) + +storage = Storage() diff --git a/app/core/video_queue.py b/app/core/video_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf57f6326edb08d7e365c9b6aa1351e8383125f --- /dev/null +++ b/app/core/video_queue.py @@ -0,0 +1,22 @@ +import json +from app.core.redis import redis_client + +class VideoQueue: + def __init__(self): + self.redis = redis_client + self.queue_name = "video_tasks" + + def push_task(self, video_id: str, task_id: str, target_format: str = "home"): + """ + Pushes a video transcoding task to the Redis queue for the Rust worker. + """ + task_data = { + "video_id": str(video_id), + "task_id": str(task_id), + "target_format": target_format + } + self.redis.lpush(self.queue_name, json.dumps(task_data)) + return task_id + +# Global instance +video_queue = VideoQueue() diff --git a/app/core/ws_manager.py b/app/core/ws_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..c675cb3af516d219ac6a6237ca72c0488cb9bb77 --- /dev/null +++ b/app/core/ws_manager.py @@ -0,0 +1,72 @@ +""" +WebSocket connection manager for real-time chat message delivery. + +Maintains an in-memory mapping of user_id -> list[WebSocket] so that +a single user can have multiple active device connections. + +Messages are dispatched to all active sockets for a given user_id. +If the recipient is offline, the message stays in the transient DB +mailbox and will be picked up on the next poll/reconnect. +""" + +from fastapi import WebSocket +from typing import Dict, List +import json +import logging + +logger = logging.getLogger("monteeq.ws") + + +class ConnectionManager: + """Manages active WebSocket connections per user.""" + + def __init__(self): + # user_id -> list of active WebSocket connections (multi-device) + self._connections: Dict[int, List[WebSocket]] = {} + + async def connect(self, user_id: int, websocket: WebSocket): + await websocket.accept() + if user_id not in self._connections: + self._connections[user_id] = [] + self._connections[user_id].append(websocket) + logger.info(f"WS connected: user={user_id}, total={len(self._connections[user_id])}") + + def disconnect(self, user_id: int, websocket: WebSocket): + if user_id in self._connections: + self._connections[user_id] = [ + ws for ws in self._connections[user_id] if ws is not websocket + ] + if not self._connections[user_id]: + del self._connections[user_id] + logger.info(f"WS disconnected: user={user_id}") + + def is_online(self, user_id: int) -> bool: + return user_id in self._connections and len(self._connections[user_id]) > 0 + + async def send_to_user(self, user_id: int, data: dict): + """Send a JSON message to all active connections for a user.""" + if user_id not in self._connections: + return False + + payload = json.dumps(data) + disconnected = [] + for ws in self._connections[user_id]: + try: + await ws.send_text(payload) + except Exception: + disconnected.append(ws) + + # Clean up any broken connections + for ws in disconnected: + self.disconnect(user_id, ws) + + return True + + async def broadcast_to_conversation(self, user_ids: List[int], data: dict): + """Send a message to all devices of all users in a conversation.""" + for uid in user_ids: + await self.send_to_user(uid, data) + + +# Singleton instance +manager = ConnectionManager() diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/crud/achievement.py b/app/crud/achievement.py new file mode 100644 index 0000000000000000000000000000000000000000..0fd87c005f1b5f76581af71f23a7c2284183d48c --- /dev/null +++ b/app/crud/achievement.py @@ -0,0 +1,43 @@ +from sqlalchemy.orm import Session +from app.models.models import Achievement +from app.schemas import schemas +from datetime import datetime + +from app.crud import notification as crud_notification +from app.schemas import notification as notification_schemas + +def get_achievements(db: Session, user_id: int): + return db.query(Achievement).filter(Achievement.user_id == user_id).all() + +def create_achievement(db: Session, user_id: int, milestone_name: str): + existing = db.query(Achievement).filter( + Achievement.user_id == user_id, + Achievement.milestone_name == milestone_name + ).first() + + if existing: + return existing + + db_achievement = Achievement( + user_id=user_id, + milestone_name=milestone_name, + reached_at=datetime.now() + ) + db.add(db_achievement) + db.commit() + db.refresh(db_achievement) + + # Create notification + # Clean up milestone name for display (e.g. FIRST_UPLOAD -> First Upload) + display_name = milestone_name.replace("_", " ").title() + crud_notification.create_notification( + db, + notification_schemas.NotificationCreate( + user_id=user_id, + message=f"You earned a new badge: {display_name}!", + type="achievement", + link="/achievements" + ) + ) + + return db_achievement diff --git a/app/crud/monetization.py b/app/crud/monetization.py new file mode 100644 index 0000000000000000000000000000000000000000..df9258194921ac612d6efc4029320f2b33bdae5d --- /dev/null +++ b/app/crud/monetization.py @@ -0,0 +1,112 @@ +from decimal import Decimal +from sqlalchemy.orm import Session +from app.models.models import Wallet, Transaction, User, Video + +def get_or_create_wallet(db: Session, user_id: int) -> Wallet: + wallet = db.query(Wallet).filter(Wallet.user_id == user_id).first() + if not wallet: + wallet = Wallet(user_id=user_id, balance=Decimal('0.00')) + db.add(wallet) + db.commit() + + db.refresh(wallet) + return wallet + +def calculate_view_earnings(views: int) -> Decimal: + """Fixed earning rate: ₦99.00 for every 1000 views""" + return Decimal('99.00') + +def credit_view_milestone(db: Session, video_id: int) -> Transaction: + video = db.query(Video).filter(Video.id == video_id).first() + if not video or not video.owner_id: + return None + + wallet = get_or_create_wallet(db, video.owner_id) + amount = calculate_view_earnings(video.views) + + # Ensure idempotency: checking if we already paid for this exact milestone. + # Note: reference_id format 'video_ID_VIEWS' + ref_id = f"video_{video.id}_{video.views}" + existing = db.query(Transaction).filter(Transaction.reference_id == ref_id).first() + if existing: + return existing + + transaction = Transaction( + wallet_id=wallet.id, + amount=amount, + transaction_type='view_milestone', + reference_id=ref_id, + description=f"Earnings for reaching {video.views} views." + ) + + wallet.balance += amount + video.earnings = (video.earnings or 0.0) + float(amount) + db.add(transaction) + db.add(video) + db.commit() + db.refresh(transaction) + return transaction + +def process_tip(db: Session, from_user_id: int, to_user_id: int, amount: float) -> Transaction: + dec_amount = Decimal(str(amount)) + + sender_wallet = get_or_create_wallet(db, from_user_id) + receiver_wallet = get_or_create_wallet(db, to_user_id) + + if sender_wallet.balance < dec_amount: + return None # Should be handled by API check, but good for safety + + # 1. Debit Sender + sender_wallet.balance -= dec_amount + sender_tx = Transaction( + wallet_id=sender_wallet.id, + amount=-dec_amount, + transaction_type='tip_sent', + reference_id=f"user_{to_user_id}", + description=f"Tip sent to user {to_user_id}" + ) + db.add(sender_tx) + + # 2. Credit Recipient + receiver_wallet.balance += dec_amount + receiver_tx = Transaction( + wallet_id=receiver_wallet.id, + amount=dec_amount, + transaction_type='tip_received', + reference_id=f"user_{from_user_id}", + description=f"Tip received from user {from_user_id}" + ) + db.add(receiver_tx) + db.add(sender_wallet) + db.add(receiver_wallet) + + db.commit() + db.refresh(sender_wallet) + db.refresh(receiver_wallet) + db.refresh(receiver_tx) + return receiver_tx + +def verify_deposit(db: Session, user_id: int, amount: float, reference: str) -> Transaction: + dec_amount = Decimal(str(amount)) + wallet = get_or_create_wallet(db, user_id) + + # Check for existing reference to prevent double funding + existing = db.query(Transaction).filter(Transaction.reference_id == reference).first() + if existing: + return existing + + transaction = Transaction( + wallet_id=wallet.id, + amount=dec_amount, + transaction_type='deposit', + reference_id=reference, + description="Wallet Top-up via Paystack" + ) + + wallet.balance += dec_amount + db.add(transaction) + db.add(wallet) + db.commit() + db.refresh(wallet) + db.refresh(transaction) + return transaction diff --git a/app/crud/notification.py b/app/crud/notification.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa1b7b8a5423e9e14f79c874e94cfe5cc05eaad --- /dev/null +++ b/app/crud/notification.py @@ -0,0 +1,80 @@ +from sqlalchemy.orm import Session +from app.models.models import Notification, PushSubscription +from app.schemas import notification as schemas +from app.schemas import push as push_schemas + +def create_notification(db: Session, notification: schemas.NotificationCreate): + db_notification = Notification( + user_id=notification.user_id, + message=notification.message, + link=notification.link, + type=notification.type + ) + db.add(db_notification) + db.commit() + db.refresh(db_notification) + return db_notification + +def get_unread_notifications(db: Session, user_id: int): + return db.query(Notification).filter( + Notification.user_id == user_id, + Notification.is_read == False + ).order_by(Notification.created_at.desc()).all() + +def mark_notification_read(db: Session, notification_id: int, user_id: int): + notification = db.query(Notification).filter( + Notification.id == notification_id, + Notification.user_id == user_id + ).first() + if notification: + notification.is_read = True + db.commit() + db.refresh(notification) + return notification + +def mark_all_notifications_read(db: Session, user_id: int): + db.query(Notification).filter( + Notification.user_id == user_id, + Notification.is_read == False + ).update({"is_read": True}) + db.commit() + return True + +def get_notifications(db: Session, user_id: int, skip: int = 0, limit: int = 50): + return db.query(Notification).filter( + Notification.user_id == user_id + ).order_by(Notification.created_at.desc()).offset(skip).limit(limit).all() + +def create_push_subscription(db: Session, subscription: push_schemas.PushSubscriptionCreate, user_id: int): + # Check if exists + db_sub = db.query(PushSubscription).filter(PushSubscription.endpoint == subscription.endpoint).first() + if db_sub: + db_sub.user_id = user_id + db_sub.p256dh = subscription.p256dh + db_sub.auth = subscription.auth + else: + db_sub = PushSubscription( + user_id=user_id, + endpoint=subscription.endpoint, + p256dh=subscription.p256dh, + auth=subscription.auth + ) + db.add(db_sub) + + db.commit() + db.refresh(db_sub) + return db_sub + +def delete_push_subscription(db: Session, endpoint: str, user_id: int): + db_sub = db.query(PushSubscription).filter( + PushSubscription.endpoint == endpoint, + PushSubscription.user_id == user_id + ).first() + if db_sub: + db.delete(db_sub) + db.commit() + return True + return False + +def get_user_push_subscriptions(db: Session, user_id: int): + return db.query(PushSubscription).filter(PushSubscription.user_id == user_id).all() diff --git a/app/crud/setting.py b/app/crud/setting.py new file mode 100644 index 0000000000000000000000000000000000000000..411d0aea01c4eefff79c5b63da46d54a55c09361 --- /dev/null +++ b/app/crud/setting.py @@ -0,0 +1,17 @@ +from sqlalchemy.orm import Session +from app.models.models import Setting + +def get_setting(db: Session, key: str) -> str: + setting = db.query(Setting).filter(Setting.key == key).first() + return setting.value if setting else None + +def update_setting(db: Session, key: str, value: str): + setting = db.query(Setting).filter(Setting.key == key).first() + if setting: + setting.value = value + else: + setting = Setting(key=key, value=value) + db.add(setting) + db.commit() + db.refresh(setting) + return setting diff --git a/app/crud/user.py b/app/crud/user.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2163928db60c7c2bfc4313dffbb21dabc20a90 --- /dev/null +++ b/app/crud/user.py @@ -0,0 +1,302 @@ +from sqlalchemy.orm import Session +from sqlalchemy import func +from app.schemas import schemas +from app.core import security +from app.models.models import User, Follow, Video, Like, Post, VerificationCode, ChallengeEntry, Challenge +from datetime import datetime, timedelta +import random +import string +import httpx + +def get_country_from_ip(ip: str): + if not ip or ip in ["127.0.0.1", "localhost"]: + return "Unknown" + try: + response = httpx.get(f"https://ipapi.co/{ip}/country_name/", timeout=2.0) + if response.status_code == 200: + return response.text.strip() + except Exception as e: + print(f"Geo-location error for {ip}: {e}") + return "Unknown" + +def get_user_by_username(db: Session, username: str): + return db.query(User).filter(User.username.ilike(username)).first() + +def get_user_by_email(db: Session, email: str): + return db.query(User).filter(User.email.ilike(email)).first() + +def create_user(db: Session, user: schemas.UserCreate, google_id: str = None, is_onboarded: bool = False, ip_address: str = None): + hashed_password = security.get_password_hash(user.password) if user.password else None + + # Get user count for admin assignment + user_count = db.query(func.count(User.id)).scalar() or 0 + is_first_user = user_count == 0 + is_requested_admin = user.username.lower() == "smasduq" + + role = "admin" if (is_first_user or is_requested_admin) else "user" + + # Automated country collection + detected_country = user.country + if not detected_country and ip_address: + detected_country = get_country_from_ip(ip_address) + + db_user = User( + username=user.username, + email=user.email, + full_name=user.full_name, + profile_pic=user.profile_pic, + hashed_password=hashed_password, + google_id=google_id, + is_onboarded=is_onboarded, + role=role, + country=detected_country + ) + + db.add(db_user) + db.commit() + db.refresh(db_user) + return db_user + +def update_user_role(db: Session, user_id: int, role: str): + user = db.query(User).filter(User.id == user_id).first() + if user: + user.role = role + db.commit() + db.refresh(user) + return user + +def update_password(db: Session, user_id: int, passwords: schemas.PasswordChange): + user = db.query(User).filter(User.id == user_id).first() + if not user: + return None + + if not security.verify_password(passwords.current_password, user.hashed_password): + return False + + user.hashed_password = security.get_password_hash(passwords.new_password) + db.commit() + db.refresh(user) + return True + +def update_user(db: Session, user_id: int, user_update: schemas.UserUpdate): + user = db.query(User).filter(User.id == user_id).first() + if not user: + return None + + if user_update.username: + user.username = user_update.username + if user_update.full_name: + user.full_name = user_update.full_name + if user_update.profile_pic: + user.profile_pic = user_update.profile_pic + if user_update.bio is not None: + user.bio = user_update.bio + if user_update.is_onboarded is not None: + user.is_onboarded = user_update.is_onboarded + if user_update.interests is not None: + user.interests = user_update.interests + if user_update.referral_source is not None: + user.referral_source = user_update.referral_source + if user_update.goals is not None: + user.goals = user_update.goals + if user_update.show_wins is not None: + user.show_wins = user_update.show_wins + if user_update.show_trophies is not None: + user.show_trophies = user_update.show_trophies + + # Notification Preferences + if user_update.notif_new_follower is not None: + user.notif_new_follower = user_update.notif_new_follower + if user_update.notif_challenge_win is not None: + user.notif_challenge_win = user_update.notif_challenge_win + if user_update.notif_comments is not None: + user.notif_comments = user_update.notif_comments + if user_update.notif_likes is not None: + user.notif_likes = user_update.notif_likes + + if user_update.email_weekly is not None: + user.email_weekly = user_update.email_weekly + if user_update.email_challenges is not None: + user.email_challenges = user_update.email_challenges + if user_update.email_payouts is not None: + user.email_payouts = user_update.email_payouts + if user_update.email_marketing is not None: + user.email_marketing = user_update.email_marketing + + # Account & Security + if user_update.payout_method is not None: + user.payout_method = user_update.payout_method + if user_update.two_factor_enabled is not None: + user.two_factor_enabled = user_update.two_factor_enabled + + db.commit() + db.refresh(user) + return user + +def get_user_by_id(db: Session, user_id: int): + return db.query(User).filter(User.id == user_id).first() + +def get_user_profile(db: Session, username: str, current_user_id: int = None): + db_user = get_user_by_username(db, username) + if not db_user: + return None + + user_id = db_user.id + + # Counts + followers_count = db.query(func.count(Follow.follower_id)).filter(Follow.following_id == user_id).scalar() or 0 + following_count = db.query(func.count(Follow.following_id)).filter(Follow.follower_id == user_id).scalar() or 0 + + # Total Views & Likes + total_views = db.query(func.sum(Video.views)).filter(Video.owner_id == user_id).scalar() or 0 + total_likes = db.query(func.count(Like.id)).join(Video).filter(Video.owner_id == user_id).scalar() or 0 + + is_following = False + if current_user_id: + is_following = db.query(Follow).filter(Follow.follower_id == current_user_id, Follow.following_id == user_id).first() is not None + + # Videos - Fetch only live (approved) videos for public, but all statuses for the owner + if current_user_id == user_id: + all_videos = db.query(Video).filter(Video.owner_id == user_id).all() + else: + all_videos = db.query(Video).filter(Video.owner_id == user_id, Video.status == "approved").all() + videos = [v for v in all_videos if v.video_type == "home"] + flash_videos = [v for v in all_videos if v.video_type == "flash"] + + # Sort videos to find most popular + sorted_videos = sorted(all_videos, key=lambda x: x.views or 0, reverse=True) + most_popular = sorted_videos[0] if sorted_videos else None + + # Identify Featured Video (Pinned or Popular) + featured_video = db_user.pinned_video + + if not featured_video and most_popular: + featured_video = most_popular + + # Posts + posts = db.query(Post).filter(Post.owner_id == user_id).all() + + # Liked Videos + liked_videos = db.query(Video).join(Like).filter(Like.user_id == user_id).all() + + # Trophies (Won Challenges) + trophies = db.query(ChallengeEntry).filter( + ChallengeEntry.user_id == user_id, + ChallengeEntry.is_winner == True + ).all() + + profile_data = { + "id": db_user.id, + "username": db_user.username, + "email": db_user.email, + "full_name": db_user.full_name, + "profile_pic": db_user.profile_pic, + "is_premium": db_user.is_premium, + "is_verified": db_user.is_verified, + "is_onboarded": db_user.is_onboarded, + "flash_uploads": db_user.flash_uploads, + "home_uploads": db_user.home_uploads, + "bio": db_user.bio, + "role": db_user.role, + "google_id": db_user.google_id, + "flash_quota_limit": db_user.flash_quota_limit, + "home_quota_limit": db_user.home_quota_limit, + "show_wins": db_user.show_wins, + "show_trophies": db_user.show_trophies, + + "followers_count": followers_count, + "following_count": following_count, + "total_views": total_views, + "total_likes": total_likes, + "featured_video": featured_video, + "most_popular_video": most_popular, + "videos_count": len(videos), + "flash_videos_count": len(flash_videos), + "posts_count": len(posts), + "videos": videos, + "flash_videos": flash_videos, + "posts": posts, + "liked_videos": liked_videos, + "trophies": trophies, + "is_following": is_following + } + return profile_data + +from app.crud import achievement as crud_achievement +from app.crud import notification as crud_notification +from app.utils.push import notify_user_push +from app.schemas.notification import NotificationCreate + +def toggle_follow(db: Session, follower_id: int, following_id: int): + if follower_id == following_id: + return False + + existing = db.query(Follow).filter(Follow.follower_id == follower_id, Follow.following_id == following_id).first() + + if existing: + db.delete(existing) + db.commit() + return False + else: + new_follow = Follow(follower_id=follower_id, following_id=following_id) + db.add(new_follow) + db.commit() + return True + +def handle_follow_side_effects(db: Session, follower_id: int, following_id: int): + """Secondary tasks after a user follows another.""" + # 1. Check for achievements + follower_count = db.query(func.count(Follow.follower_id)).filter(Follow.following_id == following_id).scalar() + + if follower_count == 1: + crud_achievement.create_achievement(db, user_id=following_id, milestone_name="FIRST_FOLLOWER") + elif follower_count == 100: + crud_achievement.create_achievement(db, user_id=following_id, milestone_name="100_FOLLOWERS") + elif follower_count == 1000: + crud_achievement.create_achievement(db, user_id=following_id, milestone_name="1K_FOLLOWERS") + + # 2. Notify user + try: + follower = get_user_by_id(db, follower_id) + msg = f"{follower.username} started following you!" + notify_user_push(db, following_id, "New Follower!", msg, link=f"/profile/{follower.username}", n_type="follower") + except Exception as e: + import logging + logging.getLogger(__name__).error(f"Failed to handle follow side effects: {e}") + +def create_verification_code(db: Session, email: str): + # Delete existing codes + db.query(VerificationCode).filter(VerificationCode.email == email).delete() + + code = ''.join(random.choices(string.digits, k=6)) + expires_at = datetime.now() + timedelta(minutes=10) + + ver_code = VerificationCode( + email=email, + code=code, + expires_at=expires_at + ) + db.add(ver_code) + db.commit() + return code + +def verify_code(db: Session, email: str, code: str): + db_code = db.query(VerificationCode).filter(VerificationCode.email.ilike(email), VerificationCode.code == code).first() + if not db_code: + return False + + if db_code.expires_at < datetime.now(): + db.delete(db_code) + db.commit() + return False + + # Success + db.delete(db_code) + db.commit() + return True + +def get_followers(db: Session, user_id: int, skip: int = 0, limit: int = 100): + return db.query(User).join(Follow, User.id == Follow.follower_id).filter(Follow.following_id == user_id).offset(skip).limit(limit).all() + +def get_following(db: Session, user_id: int, skip: int = 0, limit: int = 100): + return db.query(User).join(Follow, User.id == Follow.following_id).filter(Follow.follower_id == user_id).offset(skip).limit(limit).all() diff --git a/app/crud/video.py b/app/crud/video.py new file mode 100644 index 0000000000000000000000000000000000000000..d249abdbd2421d36dd759fd8cf2458bfd92be40b --- /dev/null +++ b/app/crud/video.py @@ -0,0 +1,573 @@ +from sqlalchemy.orm import Session, joinedload +from sqlalchemy import func, desc, text, or_ +from app.models.models import Video, Like, Comment, View, User, Post, SponsoredAd +from app.schemas import schemas +from datetime import datetime, timedelta +from typing import Optional, Union +import logging + +logger = logging.getLogger(__name__) + +VIEW_COUNT_WINDOW_HOURS = 10 +MAX_VIEWS_PER_WINDOW = 5 +INTEREST_BOOST_PER_TAG = 0.2 +TRENDING_WINDOW_DAYS = 7 +FAILED_VIDEO_VISIBILITY_HOURS = 24 + +def get_videos(db: Session, video_type: Optional[str] = None, filter_status: str = "approved", current_user_id: Optional[int] = None, skip: int = 0, limit: int = 100, mood: Optional[str] = None, feed_mode: Optional[str] = None): + from app.models.models import Follow + query = db.query(Video).options(joinedload(Video.owner)) + twenty_four_hours_ago = datetime.now() - timedelta(hours=FAILED_VIDEO_VISIBILITY_HOURS) + + # Filtering Logic based on status + if filter_status == "approved": + # Public feed: show only approved videos EXCEPT for the owner who should also see: + # 1. Recently failed videos (for retry/viewing failure) + # 2. Pending videos (currently being processed) + if current_user_id: + query = query.filter( + or_( + (Video.status == "approved") & (Video.video_url != "") & (Video.video_url.isnot(None)), + (Video.status == "pending") & (Video.owner_id == current_user_id), + (Video.status == "failed") & (Video.failed_at >= twenty_four_hours_ago) & (Video.owner_id == current_user_id) + ) + ) + else: + query = query.filter( + Video.status == "approved", + Video.video_url != "", + Video.video_url.isnot(None) + ) + elif filter_status: + query = query.filter(Video.status == filter_status) + else: + # Default behavior (no status filter): exclude old failures + query = query.filter( + ~((Video.status == "failed") & (Video.failed_at < twenty_four_hours_ago)) + ) + + if video_type: + query = query.filter(Video.video_type == video_type) + + if mood: + query = query.filter(Video.tags.ilike(f"%{mood}%")) + + # Following feed: restrict to videos from accounts the user follows + if feed_mode == 'following' and current_user_id: + followed_ids = db.query(Follow.following_id).filter(Follow.follower_id == current_user_id).subquery() + query = query.filter(Video.owner_id.in_(followed_ids)) + + # Personalization: Get user interests for boosting + user_interests = [] + if current_user_id: + # Optimized: only select interests column + user_data = db.query(User.interests).filter(User.id == current_user_id).first() + if user_data and user_data.interests: + user_interests = [t.strip().lower() for t in user_data.interests.split(",") if t.strip()] + + # Ordering: trending sorts by recent engagement, default is discovery score + if feed_mode == 'trending': + week_ago = datetime.now() - timedelta(days=TRENDING_WINDOW_DAYS) + query = query.filter(Video.created_at >= week_ago) + query = query.order_by(desc(Video.likes_count + Video.views)) + else: + # Order by discovery score by default + query = query.order_by(desc(Video.discovery_score), desc(Video.created_at)) + + videos = query.offset(skip).limit(limit).all() + + # Re-sort in memory for complex interest matching & discovery score balance + if user_interests: + for video in videos: + video_tags = [t.strip().lower() for t in (video.tags or "").split(",") if t.strip()] + # Count matches + match_count = sum(1 for t in user_interests if t in video_tags) + # Combine discovery score with interest boost (20% boost per matching tag) + video.personalized_score = video.discovery_score * (1 + (INTEREST_BOOST_PER_TAG * match_count)) + video.interest_match_score = match_count + + videos.sort(key=lambda x: x.personalized_score, reverse=True) + + if current_user_id and videos: + video_ids = [v.id for v in videos] + liked_result = db.query(Like.video_id).filter(Like.user_id == current_user_id, Like.video_id.in_(video_ids)).all() + liked_video_ids = {r[0] for r in liked_result} + for video in videos: + video.liked_by_user = video.id in liked_video_ids + else: + for video in videos: + video.liked_by_user = False + + return videos + +def search_videos(db: Session, query_str: str, status: str = "approved", current_user_id: int = None): + query = db.query(Video).options(joinedload(Video.owner)) + if status == "approved" and current_user_id: + twenty_four_hours_ago = datetime.now() - timedelta(hours=FAILED_VIDEO_VISIBILITY_HOURS) + query = query.filter( + or_( + Video.status == "approved", + (Video.status == "pending") & (Video.owner_id == current_user_id), + (Video.status == "failed") & (Video.failed_at >= twenty_four_hours_ago) & (Video.owner_id == current_user_id) + ) + ) + elif status: + query = query.filter(Video.status == status) + + if query_str: + # Check if it's a tag search (starts with #) + if query_str and query_str.startswith("#"): + tag = query_str[1:].strip() + query = query.filter(Video.tags.ilike(f"%{tag}%")) + else: + from sqlalchemy import or_ + query = query.filter( + or_( + Video.title.ilike(f"%{query_str}%"), + Video.description.ilike(f"%{query_str}%"), + Video.tags.ilike(f"%{query_str}%") + ) + ) + + videos = query.all() + + if current_user_id and videos: + video_ids = [v.id for v in videos] + liked_result = db.query(Like.video_id).filter(Like.user_id == current_user_id, Like.video_id.in_(video_ids)).all() + liked_video_ids = {r[0] for r in liked_result} + for video in videos: + video.liked_by_user = video.id in liked_video_ids + else: + for video in videos: + video.liked_by_user = False + + return videos + +def search_posts(db: Session, query_str: str, current_user_id: int = None): + query = db.query(Post) + + if query_str: + # Check if it's a tag search (starts with #) + if query_str and query_str.startswith("#"): + tag = query_str[1:].strip() + query = query.filter(Post.tags.ilike(f"%{tag}%")) + else: + from sqlalchemy import or_ + query = query.filter( + or_( + Post.content.ilike(f"%{query_str}%"), + Post.tags.ilike(f"%{query_str}%") + ) + ) + + posts = query.order_by(desc(Post.discovery_score), Post.created_at.desc()).all() + + if current_user_id and posts: + post_ids = [p.id for p in posts] + liked_result = db.query(Like.post_id).filter(Like.user_id == current_user_id, Like.post_id.in_(post_ids)).all() + liked_post_ids = {r[0] for r in liked_result} + for post in posts: + post.liked_by_user = post.id in liked_post_ids + else: + for post in posts: + post.liked_by_user = False + + return posts + +def get_video(db: Session, video_id: Union[int, str], current_user_id: int = None): + if isinstance(video_id, str) and not video_id.isdigit(): + video = db.query(Video).options(joinedload(Video.owner)).filter(Video.public_id == video_id).first() + else: + video = db.query(Video).options(joinedload(Video.owner)).filter(Video.id == int(video_id)).first() + + if not video: + return None + + if current_user_id: + video.liked_by_user = db.query(Like).filter(Like.video_id == video.id, Like.user_id == current_user_id).first() is not None + else: + video.liked_by_user = False + + return video + +from app.crud import achievement as crud_achievement +from app.crud import notification as crud_notification +from app.utils.push import notify_user_push +from app.schemas.notification import NotificationCreate + +def create_video(db: Session, video: schemas.VideoCreate, user_id: int): + # Separate additional fields from model_dump if necessary or assume model matches + # schemas.VideoCreate has fields that match Video model except processing_key might be handled + video_data = video.model_dump() + db_video = Video(**video_data, owner_id=user_id) + db.add(db_video) + db.commit() + db.refresh(db_video) + return db_video + +def create_post(db: Session, post: schemas.PostCreate, user_id: int): + post_data = post.model_dump() + db_post = Post(**post_data, owner_id=user_id) + db.add(db_post) + db.commit() + db.refresh(db_post) + return db_post + +def toggle_like(db: Session, user_id: int, video_id: Optional[int] = None, post_id: Optional[int] = None, comment_id: Optional[int] = None): + if video_id: + existing = db.query(Like).filter(Like.user_id == user_id, Like.video_id == video_id).first() + if existing: + db.delete(existing) + db.query(Video).filter(Video.id == video_id).update({"likes_count": Video.likes_count - 1}, synchronize_session=False) + db.commit() + return False + else: + new_like = Like(user_id=user_id, video_id=video_id) + db.add(new_like) + db.query(Video).filter(Video.id == video_id).update({"likes_count": Video.likes_count + 1}, synchronize_session=False) + db.commit() + return True + + if post_id: + existing = db.query(Like).filter(Like.user_id == user_id, Like.post_id == post_id).first() + if existing: + db.delete(existing) + db.query(Post).filter(Post.id == post_id).update({"likes_count": Post.likes_count - 1}, synchronize_session=False) + db.commit() + return False + else: + new_like = Like(user_id=user_id, post_id=post_id) + db.add(new_like) + db.query(Post).filter(Post.id == post_id).update({"likes_count": Post.likes_count + 1}, synchronize_session=False) + db.commit() + return True + + if comment_id: + existing = db.query(Like).filter(Like.user_id == user_id, Like.comment_id == comment_id).first() + if existing: + db.delete(existing) + comment = db.query(Comment).filter(Comment.id == comment_id).first() + if comment: + comment.likes_count = (comment.likes_count or 0) - 1 + db.commit() + return False + else: + new_like = Like(user_id=user_id, comment_id=comment_id) + db.add(new_like) + comment = db.query(Comment).filter(Comment.id == comment_id).first() + if comment: + comment.likes_count = (comment.likes_count or 0) + 1 + db.commit() + return True + + return False + +def handle_like_side_effects(db: Session, user_id: int, video_id: Optional[int] = None, post_id: Optional[int] = None, comment_id: Optional[int] = None): + """ + Perform secondary tasks after a like is created: + - Update discovery score + - Update user interests + - Send push notifications + """ + # 1. Update Discovery Score + update_discovery_score(db, video_id=video_id, post_id=post_id) + + # 2. Personalization: Update user interests + if video_id: + update_user_interests_from_video(db, user_id, video_id) + + # 3. Notify owner + try: + target = None + msg = "" + link = "" + liker = db.query(User).filter(User.id == user_id).first() + + if video_id: + target = db.query(Video).filter(Video.id == video_id).first() + if target: + msg = f"{liker.username} liked your video: {target.title}" + link = f"/watch/{video_id}" + elif post_id: + target = db.query(Post).filter(Post.id == post_id).first() + if target: + msg = f"{liker.username} liked your post" + link = "/posts" + elif comment_id: + target = db.query(Comment).filter(Comment.id == comment_id).first() + if target: + msg = f"{liker.username} liked your comment" + # If it's a comment on a video, link to the video + if target.video_id: + link = f"/watch/{target.video_id}" + elif target.post_id: + link = "/posts" + + if target and target.owner_id != user_id: + notify_user_push(db, target.owner_id, "New Like!", msg, link=link, n_type="like") + except Exception as e: + import logging + logging.getLogger(__name__).error(f"Failed to handle like side effects: {e}") + +def increment_share(db: Session, video_id: int): + video = db.query(Video).filter(Video.id == video_id).first() + if video: + video.shares = (video.shares or 0) + 1 + db.commit() + db.refresh(video) + return video + return None + +def increment_view(db: Session, user_id: Optional[int] = None, video_id: Optional[int] = None, post_id: Optional[int] = None): + # Fetch target objects + video = None + if video_id: + video = db.query(Video).filter(Video.id == video_id).first() + + post = None + if post_id: + post = db.query(Post).filter(Post.id == post_id).first() + + # 1. Uploader Check: If uploader, only count 1 view ever + if user_id and video and video.owner_id == user_id: + exists = db.query(View).filter(View.video_id == video_id, View.user_id == user_id).first() + if exists: + return video + + # 2. 10-Hour Window Check (Max 5 views per 10 hours for authenticated users) + if user_id and video_id: + ten_hours_ago = datetime.now() - timedelta(hours=VIEW_COUNT_WINDOW_HOURS) + view_count = db.query(func.count(View.id)).filter( + View.video_id == video_id, + View.user_id == user_id, + View.created_at >= ten_hours_ago + ).scalar() or 0 + + if view_count >= MAX_VIEWS_PER_WINDOW: + return video + + # Record the view and update the public counter in one transaction + new_view = View(video_id=video_id, post_id=post_id, user_id=user_id) + db.add(new_view) + + if user_id and video_id: + update_user_interests_from_video(db, user_id, video_id, commit=False) + + if video: + video.views = (video.views or 0) + 1 + + if post: + post.views_count = (post.views_count or 0) + 1 + + try: + db.commit() + except Exception: + db.rollback() + logger.exception("Failed to record view for video_id=%s post_id=%s", video_id, post_id) + raise + + if video: + db.refresh(video) + update_discovery_score(db, video_id=video_id) + return video + + if post: + db.refresh(post) + update_discovery_score(db, post_id=post_id) + return post + + return None + +def update_discovery_score(db: Session, video_id: Optional[int] = None, post_id: Optional[int] = None): + try: + from app.tasks.video_tasks import update_discovery_score_task + update_discovery_score_task.delay(video_id=video_id, post_id=post_id) + except Exception as e: + import logging + logging.getLogger(__name__).warning(f"Celery task failed to enqueue (broker down?): {e}") + +def get_posts(db: Session): + return db.query(Post).all() + +def get_ads(db: Session): + return db.query(SponsoredAd).filter(SponsoredAd.is_active == True).all() + +def create_comment(db: Session, comment: schemas.CommentBase, user_id: int, video_id: Optional[int] = None, post_id: Optional[int] = None): + + + comment_data = comment.model_dump() + db_comment = Comment(**comment_data, video_id=video_id, post_id=post_id, owner_id=user_id) + # The parent_id is now handled automatically because it's in comment_data (schemas.CommentCreate) + db.add(db_comment) + + if video_id: + db.query(Video).filter(Video.id == video_id).update({"comments_count": Video.comments_count + 1}) + elif post_id: + db.query(Post).filter(Post.id == post_id).update({"comments_count": Post.comments_count + 1}) + + db.commit() + db.refresh(db_comment) + + # Update Discovery Score + update_discovery_score(db, video_id=video_id, post_id=post_id) + + # Check for Creator Boost + target = None + if video_id: + target = db.query(Video).filter(Video.id == video_id).first() + elif post_id: + target = db.query(Post).filter(Post.id == post_id).first() + + if target and target.owner_id == user_id: + target.last_owner_interaction_at = func.now() + db.commit() + + return db_comment + +def handle_comment_side_effects(db: Session, user_id: int, video_id: Optional[int] = None, post_id: Optional[int] = None): + """Secondary tasks after a comment is created.""" + try: + target = None + msg = "" + link = "" + commenter = db.query(User).filter(User.id == user_id).first() + + if video_id: + target = db.query(Video).filter(Video.id == video_id).first() + if target: + msg = f"{commenter.username} commented on your video!" + link = f"/watch/{video_id}" + elif post_id: + target = db.query(Post).filter(Post.id == post_id).first() + if target: + msg = f"{commenter.username} commented on your post!" + link = "/posts" + + if target and target.owner_id != user_id: + notify_user_push(db, target.owner_id, "New Comment!", msg, link=link, n_type="comment") + except Exception as e: + import logging + logging.getLogger(__name__).error(f"Failed to handle comment side effects: {e}") + +def get_comments(db: Session, video_id: Optional[int] = None, post_id: Optional[int] = None, current_user_id: Optional[int] = None): + query = db.query(Comment).filter(Comment.parent_id == None) # Only get root comments + if video_id: + query = query.filter(Comment.video_id == video_id) + elif post_id: + query = query.filter(Comment.post_id == post_id) + + comments = query.order_by(Comment.created_at.desc()).all() + + if current_user_id and comments: + comment_ids = [] + def collect_ids(cms): + for c in cms: + comment_ids.append(c.id) + if c.replies: + collect_ids(c.replies) + collect_ids(comments) + + liked_result = db.query(Like.comment_id).filter(Like.user_id == current_user_id, Like.comment_id.in_(comment_ids)).all() + liked_comment_ids = {r[0] for r in liked_result} + + def mark_liked(cms): + for c in cms: + c.is_liked = c.id in liked_comment_ids + if c.replies: + mark_liked(c.replies) + mark_liked(comments) + else: + def mark_not_liked(cms): + for c in cms: + c.is_liked = False + if c.replies: + mark_not_liked(c.replies) + mark_not_liked(comments) + + return comments + +def delete_video(db: Session, video_id: int): + video = db.query(Video).filter(Video.id == video_id).first() + if video: + db.delete(video) + db.commit() + return True + return False + +def update_user_interests_from_video(db: Session, user_id: int, video_id: int, commit: bool = True): + user = db.query(User).filter(User.id == user_id).first() + video = db.query(Video).filter(Video.id == video_id).first() + if not user or not video or not video.tags: + return + + # Get first 3 tags from video + new_tags = [t.strip().lower() for t in video.tags.split(",") if t.strip()][:3] + if not new_tags: + return + + current_interests = [t.strip().lower() for t in (user.interests or "").split(",") if t.strip()] + + # Add new tags if not present, keeping it as a set to avoid duplicates + updated_interests = list(dict.fromkeys(current_interests + new_tags)) + + # Keep interests list at a reasonable size (e.g., top 20 latest) + user.interests = ",".join(updated_interests[-20:]) + if commit: + db.commit() + +def update_comment(db: Session, comment_id: int, user_id: int, content: str): + comment = db.query(Comment).filter(Comment.id == comment_id).first() + if not comment: + return None + + # Only owner or admin can edit + user = db.query(User).filter(User.id == user_id).first() + if comment.owner_id != user_id and (not user or user.role != "admin"): + return False + + comment.content = content + db.commit() + db.refresh(comment) + return comment + +def delete_comment(db: Session, comment_id: int, user_id: int): + comment = db.query(Comment).filter(Comment.id == comment_id).first() + if not comment: + return None + + user = db.query(User).filter(User.id == user_id).first() + + # Permission check for deletion: + # 1. Comment owner + # 2. Content owner (video/post owner) can delete any comment on their content + # 3. Admin + + can_delete = False + if comment.owner_id == user_id or (user and user.role == "admin"): + can_delete = True + else: + # Check content ownership + if comment.video_id: + video = db.query(Video).filter(Video.id == comment.video_id).first() + if video and video.owner_id == user_id: + can_delete = True + elif comment.post_id: + post = db.query(Post).filter(Post.id == comment.post_id).first() + if post and post.owner_id == user_id: + can_delete = True + + if not can_delete: + return False + # Store these before deleting + video_id = comment.video_id + post_id = comment.post_id + + db.delete(comment) + + if video_id: + db.query(Video).filter(Video.id == video_id).update({"comments_count": Video.comments_count - 1}) + elif post_id: + db.query(Post).filter(Post.id == post_id).update({"comments_count": Post.comments_count - 1}) + + db.commit() + return True diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/db/async_session.py b/app/db/async_session.py new file mode 100644 index 0000000000000000000000000000000000000000..65536b21b4453eda7dddba960f95f77162c21e20 --- /dev/null +++ b/app/db/async_session.py @@ -0,0 +1,29 @@ +from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker +from app.core.config import DATABASE_URL + +# Convert postgresql:// to postgresql+asyncpg:// if needed +ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://") + +async_engine = create_async_engine( + ASYNC_SQLALCHEMY_DATABASE_URL, + echo=False, + future=True, + pool_size=3, # Reduced to prevent Supabase pool exhaustion (max 15 clients) + max_overflow=2, # Reduced to prevent Supabase pool exhaustion + connect_args={"statement_cache_size": 0} +) + +AsyncSessionLocal = async_sessionmaker( + bind=async_engine, + class_=AsyncSession, + expire_on_commit=False, + autocommit=False, + autoflush=False, +) + +async def get_async_db(): + async with AsyncSessionLocal() as session: + try: + yield session + finally: + await session.close() diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000000000000000000000000000000000000..860e54258aec03a0d13c61bc35f47a764211a07e --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000000000000000000000000000000000000..ec64af78a20a256d681cf87602813d0b6844b9bf --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,29 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from app.core.config import DATABASE_URL + +SQLALCHEMY_DATABASE_URL = DATABASE_URL + +# Remove check_same_thread for postgres +if SQLALCHEMY_DATABASE_URL and SQLALCHEMY_DATABASE_URL.startswith("sqlite"): + engine = create_engine( + SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} + ) +else: + engine = create_engine( + SQLALCHEMY_DATABASE_URL, + pool_size=5, # 5 persistent connections (Supabase free tier allows ~15-20) + max_overflow=5, # 5 burst connections → 10 total max + pool_timeout=30, # 30 seconds wait for a connection + pool_recycle=1800, # Recycle connections every 30 minutes + pool_pre_ping=True, # Discard stale connections before use + ) + +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/app/db/utils.py b/app/db/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b9d619f6271f3c813a257e73b3d569d3c3c9c7cb --- /dev/null +++ b/app/db/utils.py @@ -0,0 +1,28 @@ +from sqlalchemy import text +from sqlalchemy.orm import Session + + +def sync_pk_sequence(db: Session, table_name: str, column: str = "id") -> None: + """ + Realign a PostgreSQL serial/identity sequence with MAX(id) in the table. + Safe to call when rows were inserted with explicit IDs or after manual imports. + """ + if db.get_bind().dialect.name != "postgresql": + return + + max_id = db.execute( + text(f"SELECT COALESCE(MAX({column}), 0) FROM {table_name}") + ).scalar() + db.execute( + text( + "SELECT setval(" + "pg_get_serial_sequence(:table, :column), " + ":max_id, :is_called)" + ), + { + "table": table_name, + "column": column, + "max_id": max_id, + "is_called": max_id > 0, + }, + ) diff --git a/app/email_templates/__init__.py b/app/email_templates/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..60f744fa5ed5ae6a4996f0fbd5886e2129e85834 --- /dev/null +++ b/app/email_templates/__init__.py @@ -0,0 +1,5 @@ +import random + +def pick(variants: list) -> dict: + """Return a random copy variant from the list.""" + return random.choice(variants) diff --git a/app/email_templates/celebration.py b/app/email_templates/celebration.py new file mode 100644 index 0000000000000000000000000000000000000000..32c6f48070a4230fcecbd64136302ccfff531850 --- /dev/null +++ b/app/email_templates/celebration.py @@ -0,0 +1,59 @@ +# uses {username}, {milestone_value} (where applicable) + +VARIANTS = { + "welcome_anniversary": [ + { + "subject": "Happy anniversary on Monteeq, {username}!", + "heading": "One year of creating.", + "body": "It's been exactly one year since you joined Monteeq. Thank you for being a vital part of our creative community. Here's to another year of amazing edits!", + "action_text": "View Your Portfolio" + } + ], + "first_upload_anniversary": [ + { + "subject": "One year since your first upload, {username}", + "heading": "An editing milestone.", + "body": "One year ago today, you uploaded your first video to Monteeq. Look at how far your skills and edits have come since then!", + "action_text": "See Your First Video" + } + ], + "milestone_100_followers": [ + { + "subject": "You reached 100 followers on Monteeq!", + "heading": "100 followers milestone.", + "body": "Congratulations, {username} — 100 people are now following your work and waiting for your next upload. Keep the momentum going!", + "action_text": "Check Your Stats" + } + ], + "milestone_1000_followers": [ + { + "subject": "Milestone: 1,000 followers, {username}!", + "heading": "A major milestone reached.", + "body": "Incredible work! 1,000 creators are now following your journey on Monteeq. This is a massive milestone for your personal brand.", + "action_text": "Go to Dashboard" + } + ], + "milestone_10000_views": [ + { + "subject": "Your edits have reached 10,000 views!", + "heading": "10,000 views milestone.", + "body": "Outstanding! Your videos have been viewed a combined total of 10,000 times. People are watching and appreciating your work.", + "action_text": "See Analytics" + } + ], + "creator_of_the_month": [ + { + "subject": "You are a Creator of the Month on Monteeq!", + "heading": "Top creator status.", + "body": "Congratulations {username}! Due to high engagement and outstanding uploads, you've been featured as one of our Creators of the Month. A badge has been added to your profile.", + "action_text": "View Your Profile" + } + ] +} + +def pick_celebration(template_type: str) -> dict: + import random + variants_list = VARIANTS.get(template_type) + if not variants_list: + variants_list = list(VARIANTS.values())[0] + return random.choice(variants_list) diff --git a/app/email_templates/challenge_announce.py b/app/email_templates/challenge_announce.py new file mode 100644 index 0000000000000000000000000000000000000000..f148b319f3394c599148696183d4afb83aa428d2 --- /dev/null +++ b/app/email_templates/challenge_announce.py @@ -0,0 +1,18 @@ +# subject uses {title}, {prize}; body uses {end_date} +VARIANTS = [ + { + "subject": "New Challenge: {title} — Win {prize}", + "eyebrow": "New Challenge", + "body": "Submit your best edit before {end_date}. One shot, real prize money.", + }, + { + "subject": "A new challenge is live: {title}", + "eyebrow": "Now Live", + "body": "Enter before {end_date} for a chance to win {prize}. Put your best work in.", + }, + { + "subject": "{title} — Enter now", + "eyebrow": "Challenge Live", + "body": "The {title} challenge is open. Deadline is {end_date}. Show the community what you've got.", + }, +] diff --git a/app/email_templates/challenge_ending.py b/app/email_templates/challenge_ending.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f2b5f63d419fba2f721ddbd1933e23cdee78b0 --- /dev/null +++ b/app/email_templates/challenge_ending.py @@ -0,0 +1,18 @@ +# uses {title}, {prize}, {end_date} +VARIANTS = [ + { + "subject": "2 days left to enter: {title}", + "eyebrow": "Time Is Running Out", + "body": "Entries close on {end_date}. Submit your edit before the deadline — this is your last chance.", + }, + { + "subject": "Last chance: {title} closes {end_date}", + "eyebrow": "Final Hours", + "body": "The deadline for {title} is {end_date}. If you haven't entered yet, now is the time.", + }, + { + "subject": "Enter before {end_date} — {title}", + "eyebrow": "Closing Soon", + "body": "{title} is almost over. {prize} is on the line. Get your edit in before {end_date}.", + }, +] diff --git a/app/email_templates/challenge_exit.py b/app/email_templates/challenge_exit.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1bf1b76eac52d4ffce13d21692c6805291f6c2 --- /dev/null +++ b/app/email_templates/challenge_exit.py @@ -0,0 +1,23 @@ +# all use {username}, {challenge_title} +VARIANTS = [ + { + "heading": "Challenge update, {username}", + "body": "Your entry was removed from the following challenge because the video was deleted:", + "followup": "You can still compete — upload a new video to re-enter the challenge at any time.", + }, + { + "heading": "Heads up, {username}.", + "body": "Your submission was pulled from this challenge after the video was removed from your account:", + "followup": "Re-entering is straightforward — just upload a new video and submit it to the challenge.", + }, + { + "heading": "About your entry.", + "body": "Hey {username} — we removed your entry from the challenge below because the attached video no longer exists:", + "followup": "No worries — you're free to enter again with a new upload.", + }, + { + "heading": "Your submission was removed.", + "body": "{username}, your challenge entry was removed automatically after the video was deleted:", + "followup": "The challenge is still open. Upload a new video and re-enter whenever you're ready.", + }, +] diff --git a/app/email_templates/challenge_result.py b/app/email_templates/challenge_result.py new file mode 100644 index 0000000000000000000000000000000000000000..aab5a2de9331e9c19f57fe0525876fe077ebefca --- /dev/null +++ b/app/email_templates/challenge_result.py @@ -0,0 +1,21 @@ +# uses {challenge_title}, {winner_name}, {prize} +VARIANTS = [ + { + "subject": "Results: {challenge_title} — Winner announced", + "eyebrow": "Challenge Results", + "heading": "{challenge_title}", + "body": "Congratulations to {winner_name} on an outstanding edit. Watch the winning video and see what it takes.", + }, + { + "subject": "{challenge_title} has a winner", + "eyebrow": "The Results Are In", + "heading": "We have a winner.", + "body": "{winner_name} took home {prize} in {challenge_title}. Watch the winning edit below.", + }, + { + "subject": "{winner_name} won {challenge_title}", + "eyebrow": "Challenge Over", + "heading": "And the winner is...", + "body": "{winner_name} walked away with {prize} for their entry in {challenge_title}. Watch it and see why.", + }, +] diff --git a/app/email_templates/day3_nudge.py b/app/email_templates/day3_nudge.py new file mode 100644 index 0000000000000000000000000000000000000000..cea463fd2d43a6d8ea90a269d0f6a3ac8716606f --- /dev/null +++ b/app/email_templates/day3_nudge.py @@ -0,0 +1,23 @@ +# uses {username} +VARIANTS = [ + { + "subject": "Your profile is ready — add your first video", + "heading": "Your profile is missing one thing.", + "body": "Hey {username} — you signed up 3 days ago but haven't posted yet. Your profile looks a lot stronger with work in it. Even a short clip makes a difference.", + }, + { + "subject": "Start with one clip, {username}", + "heading": "Start with one clip.", + "body": "{username}, you joined a few days ago. The hardest part is posting the first one — after that it gets easier. Upload something today.", + }, + { + "subject": "Your feed is waiting", + "heading": "The feed is waiting.", + "body": "Your account is set up, {username}. Now it needs work in it. Upload your first video and let the community see what you do.", + }, + { + "subject": "3 days in — ready to post?", + "heading": "Three days in.", + "body": "Hey {username} — no video yet. That's fine. But the sooner you post, the sooner people find you. Upload something and get your profile going.", + }, +] diff --git a/app/email_templates/digest.py b/app/email_templates/digest.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8c25377b4c34cd8962d2d9dabeebe0e3ca1de7 --- /dev/null +++ b/app/email_templates/digest.py @@ -0,0 +1,37 @@ +# Weekly digest uses no personal placeholders (batch send) +WEEKLY_VARIANTS = [ + { + "subject": "This week on Monteeq", + "heading": "This week on Monteeq", + "body": "The top edits from the community this week. Watch, follow, get inspired.", + }, + { + "subject": "Top videos this week", + "heading": "What's trending this week", + "body": "Here's what the community has been watching. Five edits worth your time.", + }, + { + "subject": "What the community watched this week", + "heading": "This week's top edits", + "body": "Five videos from the Monteeq community that got the most attention this week.", + }, +] + +# Monthly stats uses {username}, {month} +MONTHLY_VARIANTS = [ + { + "subject": "Your {month} stats on Monteeq", + "heading": "{username}'s {month} recap", + "body": "Here's how your content performed last month.", + }, + { + "subject": "{month} on Monteeq — your numbers", + "heading": "Your {month} in numbers", + "body": "A quick look at how your content did on Monteeq in {month}.", + }, + { + "subject": "How you did in {month}", + "heading": "{month} recap, {username}", + "body": "Your Monteeq numbers for {month} are in. Here's the breakdown:", + }, +] diff --git a/app/email_templates/first_comment.py b/app/email_templates/first_comment.py new file mode 100644 index 0000000000000000000000000000000000000000..23f3c8e89ed1869abe93c4051051cdeb0cbb3e15 --- /dev/null +++ b/app/email_templates/first_comment.py @@ -0,0 +1,21 @@ +# uses {username}, {commenter_name}, {video_title}, {comment_content} +VARIANTS = [ + { + "subject": "New comment on your video from {commenter_name}", + "heading": "Your video got its first comment.", + "body": "{commenter_name} left a comment on your video '{video_title}':\n\n\"{comment_content}\"", + "action_text": "Reply to Comment" + }, + { + "subject": "{commenter_name} commented: \"{comment_content}\"", + "heading": "First feedback is in.", + "body": "Hey {username} — {commenter_name} commented on '{video_title}':\n\n\"{comment_content}\"", + "action_text": "View Comment" + }, + { + "subject": "Feedback on your video '{video_title}'", + "heading": "First comment.", + "body": "{commenter_name} just shared their thoughts on '{video_title}':\n\n\"{comment_content}\"", + "action_text": "Join the conversation" + } +] diff --git a/app/email_templates/first_follower.py b/app/email_templates/first_follower.py new file mode 100644 index 0000000000000000000000000000000000000000..a70ff3d2d243470a60706647a1edd0fcefbc13f1 --- /dev/null +++ b/app/email_templates/first_follower.py @@ -0,0 +1,18 @@ +# uses {username}, {follower_name} +VARIANTS = [ + { + "subject": "{follower_name} followed you", + "heading": "You've got your first follower.", + "body": "{follower_name} just followed you on Monteeq. Keep posting and your audience will keep growing.", + }, + { + "subject": "{follower_name} is following you", + "heading": "{follower_name} is watching.", + "body": "You picked up your first follower, {username}. That's how it starts — keep uploading.", + }, + { + "subject": "Your first follower on Monteeq", + "heading": "First follower.", + "body": "{follower_name} started following your work, {username}. One follower becomes many. Stay consistent.", + }, +] diff --git a/app/email_templates/first_like.py b/app/email_templates/first_like.py new file mode 100644 index 0000000000000000000000000000000000000000..b16ee4f79160d754150e7d5043070e8eb8e75d63 --- /dev/null +++ b/app/email_templates/first_like.py @@ -0,0 +1,18 @@ +# uses {username}, {liker_name}, {video_title} +VARIANTS = [ + { + "subject": "Your video got its first like", + "heading": "Someone liked your work.", + "body": "{liker_name} liked your video {video_title}. That's the first of many — keep uploading.", + }, + { + "subject": "{liker_name} liked {video_title}", + "heading": "Your first like.", + "body": "{liker_name} hit like on {video_title}. People are seeing your work, {username}. Keep it coming.", + }, + { + "subject": "People are noticing, {username}", + "heading": "People are noticing.", + "body": "{liker_name} liked {video_title}. Your first like is in — now build on it.", + }, +] diff --git a/app/email_templates/first_video.py b/app/email_templates/first_video.py new file mode 100644 index 0000000000000000000000000000000000000000..fac10b3df25d3173a6c9201a7f3d157e9a25facb --- /dev/null +++ b/app/email_templates/first_video.py @@ -0,0 +1,21 @@ +# uses {username}, {video_title}, {video_url} +VARIANTS = [ + { + "subject": "Your video is live — {video_title}", + "heading": "Your first video is live.", + "body": "Nice work, {username}. {video_title} is now on Monteeq. Share the link to get your first views and start building an audience.", + "tip": "Share your video, join an active challenge, and follow other creators in your niche.", + }, + { + "subject": "{video_title} is up", + "heading": "It's up.", + "body": "{video_title} is live on your Monteeq profile. Get it in front of people — share the link wherever your audience is.", + "tip": "Join a challenge to get more reach. Challenges put your work in front of the whole community.", + }, + { + "subject": "First one's done, {username}", + "heading": "First one's done.", + "body": "{video_title} is live on Monteeq. The first upload is always the hardest. Keep going — consistency is what builds an audience.", + "tip": "Follow other creators, engage with their work, and your profile will grow faster.", + }, +] diff --git a/app/email_templates/growth_drip.py b/app/email_templates/growth_drip.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc032ba722f9e69de12be0869a0ad06cdda882f --- /dev/null +++ b/app/email_templates/growth_drip.py @@ -0,0 +1,48 @@ +# uses {username} +VARIANTS = { + 1: [ + { + "subject": "5 things that make a great Monteeq profile", + "heading": "Let's polish your portfolio.", + "body": "Hey {username} — a great portfolio makes all the difference when other creators or hiring brands view your profile. Make sure you pin your best edit, fill out your bio, and add your skills.", + "action_text": "Edit Profile" + } + ], + 2: [ + { + "subject": "What top-viewed edits have in common", + "heading": "Editing tips from the pros.", + "body": "Analyzing top-performing videos on Monteeq shows that the first 3 seconds are crucial. Keep pacing high, choose engaging audio, and use smooth transitions to keep retention high.", + "action_text": "Browse Top Edits" + } + ], + 3: [ + { + "subject": "How creators grow faster by engaging first", + "heading": "Connect with the community.", + "body": "Monteeq is not just a showcase — it's a network. Engage with other video editors, leave feedback on their uploads, and collaborate on challenges to grow your audience faster.", + "action_text": "Discover Creators" + } + ], + 4: [ + { + "subject": "Posting consistency: what the data shows", + "heading": "Consistency is key.", + "body": "Creators who upload at least once a week see 3x higher engagement than irregular posters. Keep your timeline active by uploading works-in-progress, speed-ramps, or challenge entries.", + "action_text": "Upload an Edit" + } + ], + 5: [ + { + "subject": "Your profile is your pitch — here's how to sharpen it", + "heading": "Build your personal brand.", + "body": "When sharing your Monteeq link on social media or job applications, treat it as your interactive resume. Keep it clean, link your socials, and showcase your specific niche.", + "action_text": "Update Profile" + } + ] +} + +def pick_growth_drip(week: int) -> dict: + import random + variants_list = VARIANTS.get(week, VARIANTS[1]) + return random.choice(variants_list) diff --git a/app/email_templates/mention.py b/app/email_templates/mention.py new file mode 100644 index 0000000000000000000000000000000000000000..e371beb461ebc1234ef4a63871b9539a1cef00a8 --- /dev/null +++ b/app/email_templates/mention.py @@ -0,0 +1,15 @@ +# uses {username}, {mentioner_name}, {context_text} +VARIANTS = [ + { + "subject": "{mentioner_name} mentioned you on Monteeq", + "heading": "You were mentioned.", + "body": "{mentioner_name} mentioned you in their post/comment:\n\n\"{context_text}\"", + "action_text": "View Mention" + }, + { + "subject": "New mention from {mentioner_name}", + "heading": "Someone mentioned you.", + "body": "Hey {username} — you were tagged/mentioned by {mentioner_name}:\n\n\"{context_text}\"", + "action_text": "Join the conversation" + } +] diff --git a/app/email_templates/password_reset.py b/app/email_templates/password_reset.py new file mode 100644 index 0000000000000000000000000000000000000000..995fc5464e55d8e0bf8ffb9382d100c2aef29ef2 --- /dev/null +++ b/app/email_templates/password_reset.py @@ -0,0 +1,17 @@ +VARIANTS = [ + { + "heading": "Reset your password", + "body": "We got a request to reset your Monteeq password. Hit the button below — this link is valid for 1 hour.", + "security_note": "Didn't request this? Your account is fine — just ignore this email. The link expires automatically.", + }, + { + "heading": "Let's get you back in.", + "body": "Someone requested a password reset for this account. Click below to set a new one. The link expires in 1 hour.", + "security_note": "If that wasn't you, your account is secure. This link will expire on its own.", + }, + { + "heading": "Password reset requested.", + "body": "Use the link below to reset your Monteeq password. It stays active for 1 hour.", + "security_note": "Didn't ask for this? No action needed — the link will expire automatically.", + }, +] diff --git a/app/email_templates/pro_upgrade.py b/app/email_templates/pro_upgrade.py new file mode 100644 index 0000000000000000000000000000000000000000..90583657c1f2430f3c060b1f3dda9acd565e7723 --- /dev/null +++ b/app/email_templates/pro_upgrade.py @@ -0,0 +1,23 @@ +# subject uses {username}; heading uses {username} +VARIANTS = [ + { + "subject": "You're now on Monteeq Pro", + "heading": "You're now Pro, {username}.", + "body": "Your account has been upgraded to Monteeq Pro. Here's what you now have access to:", + }, + { + "subject": "Pro is live on your account", + "heading": "Pro is live, {username}.", + "body": "The upgrade is done. Your Monteeq Pro perks are active right now:", + }, + { + "subject": "Monteeq Pro is yours, {username}", + "heading": "{username}, you're Pro.", + "body": "It's official. Your account is now on Monteeq Pro. Here's everything that's unlocked:", + }, + { + "subject": "Welcome to Monteeq Pro", + "heading": "Welcome to Pro.", + "body": "Hey {username} — your upgrade went through. Check out what's now available on your account:", + }, +] diff --git a/app/email_templates/reengagement.py b/app/email_templates/reengagement.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e0abd6cdc892476700acf216c5f9d8b731fb21 --- /dev/null +++ b/app/email_templates/reengagement.py @@ -0,0 +1,106 @@ +# uses {username} +# Keyed by days: 3, 7, 14, 30, 60, 90 + +VARIANTS = { + 3: [ + { + "subject": "Good time to post something new", + "heading": "It's been a few days, {username}.", + "body_1": "You haven't posted in 3 days. The community has been active — new challenges, new creators, new edits going up every day.", + "body_2": "Come back and show them what you've been working on.", + }, + { + "subject": "Ready to upload, {username}?", + "heading": "Keep the momentum going.", + "body_1": "It's been 3 days since you last logged in. The best way to grow is consistency.", + "body_2": "Share an edit or check out what others are posting today.", + } + ], + 7: [ + { + "subject": "A week away from Monteeq", + "heading": "It's been a week, {username}.", + "body_1": "A lot can happen in 7 days. New challenges are live and trending video editors are sharing their latest work.", + "body_2": "Check out your feed and get inspired to post your next project.", + }, + { + "subject": "We miss your edits", + "heading": "One week offline.", + "body_1": "Hey {username} — it's been 7 days since you were active. Don't let your profile go quiet.", + "body_2": "Come back to see the latest challenges and entries.", + } + ], + 14: [ + { + "subject": "It's been two weeks, {username}", + "heading": "Two weeks offline.", + "body_1": "We haven't seen you on Monteeq for 14 days. The community is still growing and new projects are waiting for feedback.", + "body_2": "Upload your latest edit or jump into a challenge today.", + }, + { + "subject": "What are you working on?", + "heading": "Hey {username}, still editing?", + "body_1": "It's been 14 days since your last activity. We'd love to see what you've been cooking up in your timeline.", + "body_2": "Come share your latest work-in-progress on Monteeq.", + } + ], + 30: [ + { + "subject": "Good time to post something new", + "heading": "It's been a while, {username}.", + "body_1": "You haven't posted in 30 days. The community has been active — new challenges, new creators, new edits going up every day.", + "body_2": "Come back and show them what you've been working on.", + }, + { + "subject": "The community is still here, {username}", + "heading": "The feed keeps moving.", + "body_1": "It's been 30 days since your last post, {username}. Creators are uploading, challenges are live, and there's a spot in the feed with your name on it.", + "body_2": "Drop something. Even a short edit counts.", + }, + { + "subject": "30 days — come back with something", + "heading": "Still got it, {username}?", + "body_1": "A lot has happened on Monteeq while you were away. New challenges, new faces, and a community that's still creating.", + "body_2": "Pick up where you left off. Upload something today.", + }, + { + "subject": "We miss your edits, {username}", + "heading": "Your last post was 30 days ago.", + "body_1": "Hey {username} — things have been quiet on your end. The community would love to see what you've been making.", + "body_2": "Come back. Upload something. Even one video gets you back in the mix.", + } + ], + 60: [ + { + "subject": "It's been 2 months, {username}", + "heading": "Two months away.", + "body_1": "We haven't seen any new uploads or activity from you in 60 days. There are new features, challenges, and opportunities on the platform.", + "body_2": "Check out the feed to see what has changed while you were gone.", + }, + { + "subject": "We saved your spot in the feed", + "heading": "Welcome back anytime.", + "body_1": "It's been 60 days, {username}. The editing community is still sharing premium work. We'd love to have you back.", + "body_2": "Upload an edit to refresh your portfolio.", + } + ], + 90: [ + { + "subject": "Is your Monteeq profile still active?", + "heading": "Three months away.", + "body_1": "It's been 90 days since your last activity. Your account and portfolio are safe, but a lot of new opportunities have been posted recently.", + "body_2": "Log in to keep your profile active and visible to hiring creators.", + }, + { + "subject": "Keep your portfolio active", + "heading": "Still there, {username}?", + "body_1": "Your account has been inactive for 90 days. Keep your portfolio fresh so other creators and editors can find your work.", + "body_2": "Log back in to Monteeq and upload your latest reel.", + } + ] +} + +def pick_reengagement(days: int) -> dict: + import random + variants_list = VARIANTS.get(days, VARIANTS[30]) + return random.choice(variants_list) diff --git a/app/email_templates/security.py b/app/email_templates/security.py new file mode 100644 index 0000000000000000000000000000000000000000..94be10364c3c52c98f1988ccecbe0d97043a3481 --- /dev/null +++ b/app/email_templates/security.py @@ -0,0 +1,90 @@ +# uses {username}, {device_info}, {ip_address}, {location} (where applicable) + +VARIANTS = { + "new_device_login": [ + { + "subject": "New login detected on Monteeq", + "heading": "New device login", + "body": "We noticed a new login to your Monteeq account ({username}) from a new device/browser:\n\nDevice: {device_info}\nIP Address: {ip_address}\nLocation: {location}", + "action_text": "Secure Account", + }, + { + "subject": "Was this you? New login from {device_info}", + "heading": "New device detected", + "body": "A new login was recorded for your account. Details:\n\nDevice: {device_info}\nIP: {ip_address}\nLocation: {location}\n\nIf this was you, you can safely ignore this mail.", + "action_text": "Verify Activity", + } + ], + "password_changed": [ + { + "subject": "Your Monteeq password has been updated", + "heading": "Password updated", + "body": "Hey {username} — the password for your Monteeq account was recently changed. If you initiated this change, no action is needed.", + "action_text": "Secure Account", + }, + { + "subject": "Security Alert: Password changed", + "heading": "Your password was changed", + "body": "The password for your account was changed on {timestamp}. If you did not make this change, please recover your account immediately.", + "action_text": "Reset Password", + } + ], + "email_changed": [ + { + "subject": "Monteeq email address changed", + "heading": "Email update request", + "body": "The primary email address for your Monteeq account has been changed to {new_email}. We have sent a confirmation link to that address.", + "action_text": "Revert Change", + }, + { + "subject": "Security notice: Email address updated", + "heading": "Account email changed", + "body": "Your account email address was changed to {new_email}. If you did not authorize this, please contact support immediately.", + "action_text": "Contact Support", + } + ], + "account_recovery": [ + { + "subject": "Monteeq account recovery initiated", + "heading": "Account recovery request", + "body": "An account recovery process was started for your username ({username}). Use the link below to verify your identity.", + "action_text": "Recover Account", + }, + { + "subject": "Recover your Monteeq account", + "heading": "Identity verification", + "body": "Please click the button below to complete your account recovery request. This link will expire shortly.", + "action_text": "Complete Recovery", + } + ], + "suspicious_activity": [ + { + "subject": "Security Alert: Suspicious activity detected", + "heading": "Suspicious login attempt", + "body": "We blocked a suspicious login attempt on your account from {ip_address} ({location}). Please verify your credentials.", + "action_text": "Review Activity", + }, + { + "subject": "Action Required: Secure your account", + "heading": "Security alert", + "body": "Our automated systems detected unusual activity on your Monteeq account. For your security, we suggest changing your password.", + "action_text": "Change Password", + } + ], + "account_locked": [ + { + "subject": "Your Monteeq account has been locked", + "heading": "Account locked", + "body": "For security reasons, your account was temporarily locked due to too many failed login attempts. You can unlock it using the button below.", + "action_text": "Unlock Account", + } + ] +} + +def pick_security(template_type: str) -> dict: + import random + variants_list = VARIANTS.get(template_type) + if not variants_list: + # fallback to first key + variants_list = list(VARIANTS.values())[0] + return random.choice(variants_list) diff --git a/app/email_templates/social_batch.py b/app/email_templates/social_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..6e67e7ddb37164cebe0152fca69b71277c6f10db --- /dev/null +++ b/app/email_templates/social_batch.py @@ -0,0 +1,19 @@ +# uses {username}, {summary_text} +VARIANTS = [ + { + "subject": "Your daily activity recap on Monteeq", + "heading": "While you were away...", + "body": "Here is a quick summary of the interactions on your profile and videos in the last 24 hours:\n\n{summary_text}", + "action_text": "View Activity Feed" + }, + { + "subject": "New activity on your Monteeq profile", + "heading": "You've got notifications.", + "body": "Hey {username} — here's what the community has been up to on your posts and videos:\n\n{summary_text}", + "action_text": "View Notifications" + } +] + +def pick_social_batch() -> dict: + import random + return random.choice(VARIANTS) diff --git a/app/email_templates/subscription.py b/app/email_templates/subscription.py new file mode 100644 index 0000000000000000000000000000000000000000..b45dd4ef84387ce594d6a43934a8cee64fdc87eb --- /dev/null +++ b/app/email_templates/subscription.py @@ -0,0 +1,95 @@ +# uses {username}, {expiry_date}, {plan_name}, {amount} (where applicable) + +VARIANTS = { + "trial_started": [ + { + "subject": "Your Monteeq Pro trial has started", + "heading": "Welcome to Monteeq Pro Trial", + "body": "Hey {username} — your 14-day free trial of Monteeq Pro is now active. Explore unlimited 4K uploads, advanced portfolio themes, and priority rendering.", + "action_text": "Start Creating", + }, + { + "subject": "Pro features unlocked: Trial active", + "heading": "Let's make something big.", + "body": "Your Pro trial is officially live. Get ready to experience Monteeq with zero ads and priority creator benefits for the next 14 days.", + "action_text": "Explore Pro features", + } + ], + "trial_ending": [ + { + "subject": "Your Monteeq Pro trial is ending in 3 days", + "heading": "3 days left on Pro Trial", + "body": "Hey {username} — just a heads-up that your free trial of Monteeq Pro expires on {expiry_date}. Upgrade today to keep your exclusive portfolio features and analytics.", + "action_text": "Upgrade to Pro", + }, + { + "subject": "Don't lose your Pro status", + "heading": "Your trial ends soon.", + "body": "Your trial access ends on {expiry_date}. To keep uploading in 4K and using priority render queues without interruption, finalize your subscription details below.", + "action_text": "Keep Pro features", + } + ], + "trial_expired": [ + { + "subject": "Your Monteeq Pro trial has expired", + "heading": "Trial expired", + "body": "Hey {username} — your free trial of Monteeq Pro has expired. Your account has reverted to the free plan. Your existing uploads are safe, but you've lost access to advanced portfolio customization.", + "action_text": "Upgrade to Pro", + }, + { + "subject": "Go Pro again, {username}", + "heading": "Unlock Pro once more.", + "body": "Your trial is over, but you can jump back into Pro at any time to resume 4K uploads and view advanced creator metrics.", + "action_text": "See Pro Plans", + } + ], + "payment_failed": [ + { + "subject": "Action Required: Payment failed for Monteeq Pro", + "heading": "Payment failed", + "body": "We were unable to process your subscription payment of {amount} for Monteeq Pro. To avoid account downgrade, please update your billing details.", + "action_text": "Update Billing", + }, + { + "subject": "Billing Alert: Update your payment details", + "heading": "Unable to charge account", + "body": "Our charge of {amount} for your subscription failed. Please click below to verify or update your credit card details.", + "action_text": "Verify payment", + } + ], + "subscription_renewed": [ + { + "subject": "Your Monteeq Pro subscription has renewed", + "heading": "Subscription renewed", + "body": "Hey {username} — thank you for staying with us. Your Monteeq Pro subscription has successfully renewed for another billing cycle. Receipt amount: {amount}.", + "action_text": "View Receipt", + }, + { + "subject": "Receipt for your Monteeq Pro renewal", + "heading": "Successful renewal", + "body": "Your account has been billed {amount} for your Monteeq Pro renewal. Thank you for supporting the platform.", + "action_text": "Manage Billing", + } + ], + "subscription_cancelled": [ + { + "subject": "Your Monteeq Pro subscription is cancelled", + "heading": "We're sorry to see you go.", + "body": "Hey {username} — you've cancelled your Monteeq Pro subscription. You will retain Pro access until the end of your current billing period on {expiry_date}. We'd love to hear your feedback.", + "action_text": "Share Feedback", + }, + { + "subject": "Subscription cancellation confirmed", + "heading": "Cancellation confirmed", + "body": "Your Pro benefits will expire on {expiry_date}. If you change your mind, you can renew your subscription at any time with one click.", + "action_text": "Resume subscription", + } + ] +} + +def pick_subscription(template_type: str) -> dict: + import random + variants_list = VARIANTS.get(template_type) + if not variants_list: + variants_list = list(VARIANTS.values())[0] + return random.choice(variants_list) diff --git a/app/email_templates/verification.py b/app/email_templates/verification.py new file mode 100644 index 0000000000000000000000000000000000000000..be43c8b82be0b74795ba01935a8d43c264249828 --- /dev/null +++ b/app/email_templates/verification.py @@ -0,0 +1,22 @@ +VARIANTS = [ + { + "heading": "Confirm your email", + "body": "Use the code below to finish setting up your Monteeq account. It expires in 10 minutes.", + "caption": "Didn't create a Monteeq account? You can safely ignore this email.", + }, + { + "heading": "One last step.", + "body": "Enter this code and you're in. It's valid for the next 10 minutes.", + "caption": "If this wasn't you, ignore this email. No action needed.", + }, + { + "heading": "Almost there.", + "body": "Your verification code is below. Pop it in and your account is ready to go.", + "caption": "This code expires in 10 minutes. Didn't sign up? Ignore this email.", + }, + { + "heading": "Verify your account.", + "body": "Copy the code below into the Monteeq app to confirm your email address.", + "caption": "The code expires in 10 minutes. Not you? No need to do anything.", + }, +] diff --git a/app/email_templates/welcome.py b/app/email_templates/welcome.py new file mode 100644 index 0000000000000000000000000000000000000000..c7c1f2cb4751a639b0af584212ed95b7ade268fb --- /dev/null +++ b/app/email_templates/welcome.py @@ -0,0 +1,19 @@ +# uses {username} +VARIANTS = [ + { + "heading": "Welcome to Monteeq, {username}.", + "body": "You're now part of a community built for video editors and motion designers. Here's how to get started:", + }, + { + "heading": "You're in, {username}.", + "body": "Your account is live. Three things to do first:", + }, + { + "heading": "Good to have you, {username}.", + "body": "Monteeq is where editors build their presence. Start here:", + }, + { + "heading": "Your account is ready.", + "body": "Hey {username} — welcome. Here are three things worth doing right now:", + }, +] diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/models/library.py b/app/models/library.py new file mode 100644 index 0000000000000000000000000000000000000000..be587848e3a6c7f5d0f00f4dc671db75bc7189ba --- /dev/null +++ b/app/models/library.py @@ -0,0 +1,54 @@ +import uuid +from sqlalchemy import Column, ForeignKey, DateTime, Integer, Boolean, String, Index, Text +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import relationship +from sqlalchemy.sql import func +from app.db.base import Base + +class WatchHistory(Base): + __tablename__ = "watch_history" + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + video_id = Column(Integer, ForeignKey("videos.id", ondelete="CASCADE"), nullable=False) + watched_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) + progress_seconds = Column(Integer, default=0) + duration_seconds = Column(Integer, default=0) + is_completed = Column(Boolean, default=False) + + user = relationship("User") + video = relationship("Video") + + __table_args__ = ( + Index("ix_history_user_id", "user_id"), + Index("ix_history_user_time", "user_id", "watched_at"), + Index("ix_history_video_id", "video_id"), + ) + +class LibraryWatchLater(Base): + __tablename__ = "library_watch_later" # Renamed to avoid clash with existing table + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + video_id = Column(Integer, ForeignKey("videos.id", ondelete="CASCADE"), nullable=False) + saved_at = Column(DateTime(timezone=True), server_default=func.now()) + + user = relationship("User") + video = relationship("Video") + + __table_args__ = ( + Index("ix_watchlater_user_id", "user_id"), + ) + +class LikedVideo(Base): + __tablename__ = "liked_videos" + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + video_id = Column(Integer, ForeignKey("videos.id", ondelete="CASCADE"), nullable=False) + liked_at = Column(DateTime(timezone=True), server_default=func.now()) + + user = relationship("User") + video = relationship("Video") + + __table_args__ = ( + Index("ix_liked_user_id", "user_id"), + ) diff --git a/app/models/models.py b/app/models/models.py new file mode 100644 index 0000000000000000000000000000000000000000..3d9f7c75d9c9fffb1769c159f79127fa78f5d72a --- /dev/null +++ b/app/models/models.py @@ -0,0 +1,661 @@ +from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, Float, Text, DateTime, func, Numeric, Index +import uuid + +from sqlalchemy.orm import relationship, backref +from app.db.base import Base +import enum +from app.core.config import BASE_URL, FLASH_QUOTA_LIMIT, HOME_QUOTA_LIMIT + +class UserRole(str, enum.Enum): + ADMIN = "admin" + USER = "user" + +class VideoType(str, enum.Enum): + HOME = "home" + FLASH = "flash" + +class ApprovalStatus(str, enum.Enum): + PENDING = "pending" + APPROVED = "approved" + REJECTED = "rejected" + FAILED = "failed" + +from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo + +class User(Base): + + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True) + username = Column(String, unique=True, index=True) + full_name = Column(String, nullable=True) + email = Column(String, unique=True, index=True) + hashed_password = Column(String, nullable=True) + google_id = Column(String, unique=True, nullable=True) + role = Column(String, default=UserRole.USER) + is_premium = Column(Boolean, default=False) + premium_expires_at = Column(DateTime(timezone=True), nullable=True) + is_verified = Column(Boolean, default=False) + is_onboarded = Column(Boolean, default=False) + profile_pic = Column(String, nullable=True) # Will use dynamic UI-Avatars if null + country = Column(String, nullable=True, index=True) # Automated tracking (ISO code or Name) + + # Personalization data + interests = Column(Text, nullable=True) # Comma-separated tags or JSON + referral_source = Column(String, nullable=True) + goals = Column(Text, nullable=True) + + # Quotas for free users + flash_uploads = Column(Integer, default=0) + home_uploads = Column(Integer, default=0) + bio = Column(String, nullable=True) + show_wins = Column(Boolean, default=True) # Show challenge wins on public profile + show_trophies = Column(Boolean, default=True) # Show Trophy Room tab on public profile + public_key = Column(Text, nullable=True) # PEM encoded public key for E2EE + + # Notification Preferences + notif_new_follower = Column(Boolean, default=True) + notif_challenge_win = Column(Boolean, default=True) + notif_comments = Column(Boolean, default=True) + notif_likes = Column(Boolean, default=False) + + email_weekly = Column(Boolean, default=True) + email_challenges = Column(Boolean, default=True) + email_payouts = Column(Boolean, default=True) + email_marketing = Column(Boolean, default=False) + + # Showcase content + pinned_video_id = Column(Integer, ForeignKey("videos.id"), nullable=True) + + # Account & Security + payout_method = Column(String, default='stripe') + two_factor_enabled = Column(Boolean, default=False) + totp_secret = Column(String, nullable=True) # For app-based 2FA + recovery_codes = Column(Text, nullable=True) # JSON list of hashed codes + is_active = Column(Boolean, default=True) # For deactivation + created_at = Column(DateTime, default=func.now(), index=True) + + # Stripe Subscriptions + stripe_customer_id = Column(String, nullable=True, index=True) + subscription_tier = Column(String, default="free") + subscription_status = Column(String, default="inactive") + subscription_id = Column(String, nullable=True) + current_period_end = Column(DateTime(timezone=True), nullable=True) + + @property + def flash_quota_limit(self): + return FLASH_QUOTA_LIMIT + + @property + def home_quota_limit(self): + return HOME_QUOTA_LIMIT + + videos = relationship("Video", back_populates="owner", foreign_keys="[Video.owner_id]") + pinned_video = relationship("Video", foreign_keys=[pinned_video_id]) + posts = relationship("Post", back_populates="owner") + reposts = relationship("Repost", back_populates="user") + comments = relationship("Comment", back_populates="owner") + # History, Likes, Watch Later + likes = relationship("Like", back_populates="user") + views = relationship("View", back_populates="user") + watch_later = relationship("WatchLater", back_populates="user") + + # Followers + followers = relationship( + "Follow", + foreign_keys="Follow.following_id", + back_populates="following", + cascade="all, delete-orphan", + ) + following = relationship( + "Follow", + foreign_keys="Follow.follower_id", + back_populates="follower", + cascade="all, delete-orphan", + ) + + +class VerificationCode(Base): + __tablename__ = "verification_codes" + + id = Column(Integer, primary_key=True, index=True) + email = Column(String, index=True) + code = Column(String) + expires_at = Column(DateTime) + created_at = Column(DateTime, default=func.now()) + +class UserSession(Base): + __tablename__ = "user_sessions" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id")) + token_hash = Column(String, index=True) # Identifying the session by token hash + device_info = Column(String, nullable=True) # Browser/OS + ip_address = Column(String, nullable=True) + last_active = Column(DateTime, default=func.now()) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User") + +def generate_public_id(): + return f"vid_{uuid.uuid4().hex[:16]}" + +class Video(Base): + __tablename__ = "videos" + + id = Column(Integer, primary_key=True, index=True) + public_id = Column(String, unique=True, index=True, nullable=True, default=generate_public_id) + title = Column(String) + description = Column(Text, nullable=True) + video_url = Column(String) # This will now be the fallback (likely 720p or original) + url_480p = Column(String, nullable=True) + url_720p = Column(String, nullable=True) + url_1080p = Column(String, nullable=True) + url_2k = Column(String, nullable=True) + url_4k = Column(String, nullable=True) + thumbnail_url = Column(String) + video_type = Column(String, index=True) # home or flash + status = Column(String, default=ApprovalStatus.PENDING, index=True) + owner_id = Column(Integer, ForeignKey("users.id"), index=True) + views = Column(Integer, default=0) + earnings = Column(Float, default=0.0) + shares = Column(Integer, default=0) + duration = Column(Integer, default=0) + processing_key = Column(String, nullable=True) + tags = Column(Text, nullable=True) # Comma-separated tags + discovery_score = Column(Float, default=0.0, index=True) + last_owner_interaction_at = Column(DateTime, nullable=True) + failed_at = Column(DateTime, nullable=True) + processing_message = Column(String, nullable=True) + created_at = Column(DateTime, default=func.now(), index=True) + likes_count = Column(Integer, default=0) + comments_count = Column(Integer, default=0) + is_exclusive = Column(Boolean, default=False) + + owner = relationship("User", back_populates="videos", foreign_keys=[owner_id]) + comments = relationship("Comment", back_populates="video", cascade="all, delete-orphan") + likes = relationship("Like", back_populates="video", cascade="all, delete-orphan") + challenge_entries = relationship("ChallengeEntry", back_populates="video", cascade="all, delete-orphan") + + @property + def owner_username(self): + return self.owner.username if self.owner else "Unknown" + + @property + def creator_name(self): + return self.owner.username if self.owner else "Unknown" + + def _resolve_url(self, url: str) -> str: + """Helper to convert stored S3 URLs to current CDN/CloudFront URLs.""" + if not url: + return url + # If it's already a full URL that doesn't match our current domain, we extract the path + if "amazonaws.com" in url or "monteeq.s3" in url or "cdn.monteeq.com" in url: + from app.core.storage import storage + # Extract the key part (everything after the domain) + # Both S3 and CDN URLs follow the pattern [domain]/[key] + if ".com/" in url: + parts = url.split(".com/") + if len(parts) > 1: + return storage.get_url(parts[1]) + return url + + @property + def dynamic_video_url(self): + return self._resolve_url(self.video_url) + + @property + def dynamic_thumbnail_url(self): + return self._resolve_url(self.thumbnail_url) + + @property + def dynamic_url_720p(self): + return self._resolve_url(self.url_720p) + + @property + def dynamic_url_1080p(self): + return self._resolve_url(self.url_1080p) + +class View(Base): + __tablename__ = "views" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), index=True) + video_id = Column(Integer, ForeignKey("videos.id"), nullable=True, index=True) + post_id = Column(Integer, ForeignKey("posts.id"), nullable=True, index=True) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User", back_populates="views") + video = relationship("Video") + post = relationship("Post") + + +class Like(Base): + __tablename__ = "likes" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), index=True) + video_id = Column(Integer, ForeignKey("videos.id"), nullable=True, index=True) + post_id = Column(Integer, ForeignKey("posts.id"), nullable=True, index=True) + comment_id = Column(Integer, ForeignKey("comments.id", ondelete="CASCADE"), nullable=True, index=True) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User", back_populates="likes") + video = relationship("Video", back_populates="likes") + post = relationship("Post", back_populates="likes") + comment = relationship("Comment", back_populates="likes") + +class Post(Base): + __tablename__ = "posts" + + id = Column(Integer, primary_key=True, index=True) + content = Column(Text) + image_url = Column(String, nullable=True) + owner_id = Column(Integer, ForeignKey("users.id"), index=True) + original_post_id = Column(Integer, ForeignKey("posts.id"), nullable=True, index=True) + views_count = Column(Integer, default=0) + tags = Column(Text, nullable=True) # Comma-separated tags + + owner = relationship("User", back_populates="posts") + original_post = relationship("Post", remote_side=[id]) + is_active = Column(Boolean, default=True) + discovery_score = Column(Float, default=0.0, index=True) + last_owner_interaction_at = Column(DateTime, nullable=True) + created_at = Column(DateTime, default=func.now(), index=True) + likes_count = Column(Integer, default=0) + comments_count = Column(Integer, default=0) + is_exclusive = Column(Boolean, default=False) + + likes = relationship("Like", back_populates="post", cascade="all, delete-orphan") + comments = relationship("Comment", back_populates="post", cascade="all, delete-orphan") + +class Comment(Base): + __tablename__ = "comments" + + id = Column(Integer, primary_key=True, index=True) + content = Column(Text) + video_id = Column(Integer, ForeignKey("videos.id"), nullable=True, index=True) + post_id = Column(Integer, ForeignKey("posts.id"), nullable=True, index=True) + parent_id = Column(Integer, ForeignKey("comments.id"), nullable=True, index=True) # Threaded replies + owner_id = Column(Integer, ForeignKey("users.id"), index=True) + likes_count = Column(Integer, default=0) + created_at = Column(DateTime, default=func.now()) + + owner = relationship("User", back_populates="comments") + video = relationship("Video", back_populates="comments") + post = relationship("Post", back_populates="comments") + replies = relationship("Comment", backref=backref("parent", remote_side=[id]), cascade="all, delete-orphan") + likes = relationship("Like", back_populates="comment", cascade="all, delete-orphan") + +class Follow(Base): + __tablename__ = "follows" + + id = Column(Integer, primary_key=True, index=True) + follower_id = Column(Integer, ForeignKey("users.id"), index=True) + following_id = Column(Integer, ForeignKey("users.id"), index=True) + created_at = Column(DateTime, default=func.now(), index=True) + + follower = relationship("User", foreign_keys=[follower_id], back_populates="following") + following = relationship("User", foreign_keys=[following_id], back_populates="followers") + +class WatchLater(Base): + __tablename__ = "watch_later" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), index=True) + video_id = Column(Integer, ForeignKey("videos.id"), index=True) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User", back_populates="watch_later") + video = relationship("Video") + + +class Repost(Base): + __tablename__ = "reposts" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id")) + video_id = Column(Integer, ForeignKey("videos.id")) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User", back_populates="reposts") + video = relationship("Video") + +class Achievement(Base): + __tablename__ = "achievements" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id")) + milestone_name = Column(String) # e.g., "100_VIEWS", "1000_VIEWS" + reached_at = Column(DateTime, default=func.now()) + + user = relationship("User") + +class SponsoredAd(Base): + __tablename__ = "sponsored_ads" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String) + image_url = Column(String) + is_active = Column(Boolean, default=True) + +class Notification(Base): + __tablename__ = "notifications" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id")) + message = Column(String) + link = Column(String, nullable=True) + type = Column(String, default="info") + is_read = Column(Boolean, default=False) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User") + +class PushSubscription(Base): + __tablename__ = "push_subscriptions" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id")) + endpoint = Column(String, unique=True, index=True) + p256dh = Column(String) + auth = Column(String) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User") + +class Conversation(Base): + __tablename__ = "conversations" + + id = Column(Integer, primary_key=True, index=True) + user1_id = Column(Integer, ForeignKey("users.id")) + user2_id = Column(Integer, ForeignKey("users.id")) + created_at = Column(DateTime, default=func.now()) + + user1 = relationship("User", foreign_keys=[user1_id]) + user2 = relationship("User", foreign_keys=[user2_id]) + messages = relationship("ChatMessage", back_populates="conversation", cascade="all, delete-orphan") + +class ChatMessage(Base): + __tablename__ = "chat_messages" + + id = Column(Integer, primary_key=True, index=True) + conversation_id = Column(Integer, ForeignKey("conversations.id")) + sender_id = Column(Integer, ForeignKey("users.id")) + encrypted_content = Column(Text) # AES-GCM encrypted blob + iv = Column(String) # Initialization Vector + recipient_key = Column(Text) # AES key wrapped with recipient's public key + sender_key = Column(Text) # AES key wrapped with sender's public key + message_type = Column(String, default="text") # text, voice, file + attachment_url = Column(String, nullable=True) + file_metadata = Column(Text, nullable=True) # JSON blob for filename, size, etc. + created_at = Column(DateTime, default=func.now()) + + conversation = relationship("Conversation", back_populates="messages") + sender = relationship("User") + +class UserDevicePrekeyBundle(Base): + __tablename__ = "user_device_prekey_bundles" + + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), primary_key=True, index=True) + device_id = Column(String, primary_key=True, index=True) + identity_key = Column(Text, nullable=False) + signed_prekey = Column(Text, nullable=False) + signed_prekey_signature = Column(Text, nullable=False) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User", backref=backref("prekey_bundles", cascade="all, delete-orphan")) + +class UserOneTimePrekey(Base): + __tablename__ = "user_one_time_prekeys" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True) + device_id = Column(String, index=True) + key_value = Column(Text, nullable=False) + used = Column(Boolean, default=False) + created_at = Column(DateTime, default=func.now()) + + user = relationship("User", backref=backref("one_time_prekeys", cascade="all, delete-orphan")) + +class Setting(Base): + __tablename__ = "settings" + key = Column(String, primary_key=True, index=True) + value = Column(String) + +class Challenge(Base): + __tablename__ = "challenges" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True) + description = Column(Text) + brand = Column(String, nullable=True) + prize = Column(String) + is_open = Column(Boolean, default=True) + is_paid = Column(Boolean, default=False) + is_gold = Column(Boolean, default=False) + entry_fee = Column(Numeric(12, 2), default=0.00) + start_date = Column(DateTime, default=func.now()) + end_date = Column(DateTime, nullable=True) + entry_count = Column(Integer, default=0) + winner_picked = Column(Boolean, default=False) + created_at = Column(DateTime, default=func.now()) + + entries = relationship("ChallengeEntry", back_populates="challenge", cascade="all, delete-orphan") + +class ChallengeEntry(Base): + __tablename__ = "challenge_entries" + + id = Column(Integer, primary_key=True, index=True) + challenge_id = Column(Integer, ForeignKey("challenges.id")) + user_id = Column(Integer, ForeignKey("users.id")) + video_id = Column(Integer, ForeignKey("videos.id")) # Requirement: Users enter with their video + is_winner = Column(Boolean, default=False) + created_at = Column(DateTime, default=func.now()) + + challenge = relationship("Challenge", back_populates="entries") + user = relationship("User") + video = relationship("Video", back_populates="challenge_entries") + + +class Wallet(Base): + __tablename__ = "wallets" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), unique=True, index=True) + balance = Column(Numeric(12, 2), default=0.00) # Precise NGN to 2 decimal places + currency = Column(String, default="NGN") + created_at = Column(DateTime, default=func.now()) + updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) + + user = relationship("User", backref=backref("wallet", uselist=False)) + transactions = relationship("Transaction", back_populates="wallet", cascade="all, delete-orphan", order_by="desc(Transaction.created_at)") + + +class Transaction(Base): + __tablename__ = "transactions" + + id = Column(Integer, primary_key=True, index=True) + wallet_id = Column(Integer, ForeignKey("wallets.id"), index=True) + amount = Column(Numeric(12, 2)) + transaction_type = Column(String, index=True) # 'view_milestone', 'tip', 'subscription', 'payout' + status = Column(String, default="success", index=True) # 'pending', 'success', 'failed' + reference_id = Column(String, nullable=True, index=True) # Stores 'video_34', 'user_1', etc. + description = Column(Text, nullable=True) + created_at = Column(DateTime, default=func.now(), index=True) + + wallet = relationship("Wallet", back_populates="transactions") + + + + + +class PayoutRequest(Base): + __tablename__ = "payout_requests" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), index=True) + wallet_id = Column(Integer, ForeignKey("wallets.id"), index=True) + amount = Column(Numeric(12, 2)) + status = Column(String, default="pending", index=True) # 'pending', 'processing', 'completed', 'rejected' + bank_details = Column(Text, nullable=True) # JSON string: { bank, account_number, account_name } + admin_note = Column(Text, nullable=True) + requested_at = Column(DateTime, default=func.now(), index=True) + processed_at = Column(DateTime, nullable=True) + + user = relationship("User") + wallet = relationship("Wallet") + + +# ─── Recommendation Engine Models ───────────────────────────────────────────── + +class VideoInteraction(Base): + """ + Stores one record per user-video interaction event. + Used by the recommendation engine to compute personalized scores. + """ + __tablename__ = "video_interactions" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True) + video_id = Column(Integer, ForeignKey("videos.id"), nullable=False, index=True) + + # Raw watch data + watch_time = Column(Float, default=0.0) # seconds actually watched + duration = Column(Float, default=0.0) # total video length in seconds + liked = Column(Boolean, default=False) + skipped = Column(Boolean, default=False) + replayed = Column(Boolean, default=False) # true if user rewound / re-watched + + # Computed at write-time for fast reads + completion_rate = Column(Float, default=0.0) # watch_time / duration + skipped_fast = Column(Boolean, default=False) # watch_time < 2 s + interaction_score = Column(Float, default=0.0) # final weighted score + + timestamp = Column(DateTime, default=func.now(), index=True) + + user = relationship("User") + video = relationship("Video") + + +class UserRecommendationProfile(Base): + """ + One row per user — stores a JSON-encoded tag→affinity mapping + so the feed can be assembled quickly without re-scanning all interactions. + Updated in background after each interaction. + """ + __tablename__ = "user_recommendation_profiles" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), unique=True, nullable=False, index=True) + + # JSON: {"footballedit": 0.85, "anime": 0.6, ...} + tag_affinity = Column(Text, default="{}") + + # JSON: [video_id, ...] — LEGACY: used for strict exclusion + seen_video_ids = Column(Text, default="[]") + + # JSON: {"video_id": {"c": count, "t": timestamp, "wt": total_watch_time, "mc": max_completion}} + watch_history = Column(Text, default="{}") + + updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) + + user = relationship("User") + +class PartnerLead(Base): + __tablename__ = "partner_leads" + + id = Column(Integer, primary_key=True, index=True) + brand_name = Column(String, index=True) + contact_email = Column(String, index=True) + campaign_type = Column(String) + details = Column(Text) + status = Column(String, default="new") # "new", "contacted", "closed" + created_at = Column(DateTime, default=func.now(), index=True) + + +class DiscoveredCategory(Base): + """ + Auto-discovered categories from video hashtags. + Only tags that pass the "meaningful" vetting filter and are approved + will be surfaced to users. + """ + __tablename__ = "discovered_categories" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String, unique=True, index=True) # Lowercase canonical tag (e.g. "football") + display_name = Column(String) # Human-readable (e.g. "Football") + count = Column(Integer, default=0) # Number of approved videos using this tag + is_approved = Column(Boolean, default=False, index=True) # Only approved categories are shown + related_tags = Column(Text, default="") # Comma-separated similar tags for semantic matching + icon_hint = Column(String, nullable=True) # Optional icon name hint (e.g. "trophy", "gamepad") + created_at = Column(DateTime, default=func.now()) + updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) + + +class EmailLog(Base): + """ + One row per sent email. Used for: + - Cooldown enforcement (can_send checks last sent_at per template) + - Deduplication (prevent double-sends on retry) + - Analytics (open/click rates per template via ESP webhooks) + - Anti-spam (daily/weekly send caps per user) + """ + __tablename__ = "email_log" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True) + template = Column(String(100), nullable=False, index=True) + subject = Column(String(300), nullable=True) + # ESP tracking — populated by webhook + sent_at = Column(DateTime, default=func.now(), nullable=False, index=True) + opened_at = Column(DateTime, nullable=True) + clicked_at = Column(DateTime, nullable=True) + bounced = Column(Boolean, default=False, index=True) + unsubscribed = Column(Boolean, default=False) + esp_message_id = Column(String(200), nullable=True, index=True) # Resend/Zoho message ID + + user = relationship("User", backref=backref("email_logs", cascade="all, delete-orphan")) + + __table_args__ = ( + Index("ix_email_log_user_template_sent", "user_id", "template", "sent_at"), + ) + + +class ContentReport(Base): + __tablename__ = "content_reports" + + id = Column(Integer, primary_key=True, index=True) + reporter_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + content_type = Column(String, nullable=False) # "video", "flash", "post", "comment" + video_id = Column(Integer, ForeignKey("videos.id", ondelete="CASCADE"), nullable=True) + post_id = Column(Integer, ForeignKey("posts.id", ondelete="CASCADE"), nullable=True) + comment_id = Column(Integer, ForeignKey("comments.id", ondelete="CASCADE"), nullable=True) + reason = Column(String, nullable=False) + description = Column(Text, nullable=True) + status = Column(String, default="pending", nullable=False) # pending, dismissed, resolved + created_at = Column(DateTime, default=func.now(), nullable=False) + resolved_at = Column(DateTime, nullable=True) + resolved_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + notes = Column(Text, nullable=True) + + reporter = relationship("User", foreign_keys=[reporter_id], backref=backref("filed_reports", cascade="all, delete-orphan")) + video = relationship("Video", foreign_keys=[video_id], backref=backref("reports", cascade="all, delete-orphan")) + post = relationship("Post", foreign_keys=[post_id], backref=backref("reports", cascade="all, delete-orphan")) + comment = relationship("Comment", foreign_keys=[comment_id], backref=backref("reports", cascade="all, delete-orphan")) + resolver = relationship("User", foreign_keys=[resolved_by]) + + +class ModerationAuditLog(Base): + __tablename__ = "moderation_audit_logs" + + id = Column(Integer, primary_key=True, index=True) + action = Column(String, nullable=False) # e.g. report_created, report_dismissed, content_deleted, user_suspended + moderator_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + target_type = Column(String, nullable=False) # video, post, comment, user + target_id = Column(String, nullable=False) + details = Column(Text, nullable=True) + created_at = Column(DateTime, default=func.now(), nullable=False) + + moderator = relationship("User", foreign_keys=[moderator_id], backref="moderation_actions") + diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/schemas/library.py b/app/schemas/library.py new file mode 100644 index 0000000000000000000000000000000000000000..07e692e387626433b2e9383ba3de4eeaa612f70e --- /dev/null +++ b/app/schemas/library.py @@ -0,0 +1,90 @@ +from pydantic import BaseModel, ConfigDict, field_serializer +from typing import List, Optional, Union +from datetime import datetime +from uuid import UUID + +# ── Base Video Schema for Library ─────────────────────────────────────────── +class LibraryVideo(BaseModel): + id: Union[int, str] # Using Union to allow serialization to string + public_id: Optional[str] = None + title: str + thumbnail_url: str + duration: int # Mapping duration_seconds to duration + views: int + owner_id: int + created_at: datetime + tags: Optional[str] = None + creator_name: Optional[str] = None + + @field_serializer('id') + def serialize_id(self, v: int) -> Union[int, str]: + return self.public_id if (hasattr(self, 'public_id') and self.public_id) else v + + model_config = ConfigDict(from_attributes=True) + +# ── History ────────────────────────────────────────────────────────────────── +class HistoryItem(BaseModel): + id: UUID + video: LibraryVideo + watched_at: datetime + progress_seconds: int + duration_seconds: int + is_completed: bool + + model_config = ConfigDict(from_attributes=True) + +class HistoryResponse(BaseModel): + items: List[HistoryItem] + page: int + limit: int + total: int + has_more: bool + +class HistoryProgressUpdate(BaseModel): + progress_seconds: int + duration_seconds: int + is_completed: bool + +class HistoryTrackRequest(BaseModel): + video_id: Union[int, str] + progress_seconds: float + duration_seconds: float + is_completed: bool + +# ── Watch Later ───────────────────────────────────────────────────────────── +class WatchLaterItem(BaseModel): + id: UUID + video: LibraryVideo + saved_at: datetime + + model_config = ConfigDict(from_attributes=True) + +class WatchLaterStats(BaseModel): + total_videos: int + total_runtime_seconds: int + new_this_week: int + +class WatchLaterResponse(BaseModel): + items: List[WatchLaterItem] + stats: WatchLaterStats + +# ── Liked Videos ───────────────────────────────────────────────────────────── +class LikedItem(BaseModel): + id: UUID + video: LibraryVideo + liked_at: datetime + + model_config = ConfigDict(from_attributes=True) + +class LikedResponse(BaseModel): + items: List[LikedItem] + page: int + limit: int + total: int + has_more: bool + +# ── Shared ─────────────────────────────────────────────────────────────────── +class LibraryStats(BaseModel): + history_count: int + watch_later_count: int + liked_count: int diff --git a/app/schemas/notification.py b/app/schemas/notification.py new file mode 100644 index 0000000000000000000000000000000000000000..151c4cbbd4f72041cc502efdc1a98976e8325e91 --- /dev/null +++ b/app/schemas/notification.py @@ -0,0 +1,19 @@ +from pydantic import BaseModel, ConfigDict +from datetime import datetime +from typing import Optional + +class NotificationBase(BaseModel): + message: str + link: Optional[str] = None + type: Optional[str] = "info" + +class NotificationCreate(NotificationBase): + user_id: int + +class Notification(NotificationBase): + id: int + user_id: int + is_read: bool + created_at: datetime + + model_config = ConfigDict(from_attributes=True) diff --git a/app/schemas/push.py b/app/schemas/push.py new file mode 100644 index 0000000000000000000000000000000000000000..5628f8f23ab28b03a67b19dfb6023d424f30a2a2 --- /dev/null +++ b/app/schemas/push.py @@ -0,0 +1,18 @@ +from pydantic import BaseModel +from datetime import datetime + +class PushSubscriptionBase(BaseModel): + endpoint: str + p256dh: str + auth: str + +class PushSubscriptionCreate(PushSubscriptionBase): + pass + +class PushSubscription(PushSubscriptionBase): + id: int + user_id: int + created_at: datetime + + class Config: + from_attributes = True diff --git a/app/schemas/report.py b/app/schemas/report.py new file mode 100644 index 0000000000000000000000000000000000000000..1d4c518bde4f745f3d5aad380a471034b6076096 --- /dev/null +++ b/app/schemas/report.py @@ -0,0 +1,46 @@ +from pydantic import BaseModel, ConfigDict +from typing import Optional, Union +from datetime import datetime + +class ReportCreate(BaseModel): + content_type: str # "video", "flash", "post", "comment" + content_id: Union[int, str] # Can be string public_id (for videos/flash) or integer ID + reason: str # spam, harassment, hate, violence, copyright, sexual, scam, other + description: Optional[str] = None + +class ReportResponse(BaseModel): + id: int + reporter_id: int + reporter_username: Optional[str] = None + content_type: str + content_id: Union[int, str] + reason: str + description: Optional[str] = None + status: str + created_at: datetime + resolved_at: Optional[datetime] = None + resolved_by: Optional[int] = None + resolver_username: Optional[str] = None + notes: Optional[str] = None + + # Extra fields for previewing reported content + reported_content_preview: Optional[str] = None + reported_content_creator: Optional[str] = None + + model_config = ConfigDict(from_attributes=True) + +class ReportAction(BaseModel): + action: str # "dismiss", "resolve", "delete_content", "suspend_user" + notes: Optional[str] = None + +class AuditLogResponse(BaseModel): + id: int + action: str + moderator_id: Optional[int] = None + moderator_username: Optional[str] = None + target_type: str + target_id: str + details: Optional[str] = None + created_at: datetime + + model_config = ConfigDict(from_attributes=True) diff --git a/app/schemas/schemas.py b/app/schemas/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..8b96a7211d80368dd4acdf3d3cc93f4ffd8ac534 --- /dev/null +++ b/app/schemas/schemas.py @@ -0,0 +1,648 @@ +from pydantic import BaseModel, ConfigDict, field_validator, field_serializer +from typing import List, Optional, Union +from datetime import datetime + +class UserBase(BaseModel): + username: str + email: str + full_name: Optional[str] = None + profile_pic: Optional[str] = None + interests: Optional[str] = None + referral_source: Optional[str] = None + goals: Optional[str] = None + country: Optional[str] = None + + @field_validator('profile_pic', mode='before') + @classmethod + def resolve_user_cdn_url(cls, v): + if not v or not isinstance(v, str): + return v + if "amazonaws.com" in v or "monteeq.s3" in v or "cdn.monteeq.com" in v: + try: + from app.core.storage import storage + if ".com/" in v: + parts = v.split(".com/") + if len(parts) > 1: + return storage.get_url(parts[1]) + except Exception: + return v + return v + + model_config = ConfigDict(from_attributes=True) + +class UserPublic(UserBase): + id: int + +class UserCreate(UserBase): + password: Optional[str] = None + + @field_validator('password') + @classmethod + def password_complexity(cls, v: Optional[str]) -> Optional[str]: + if v is None: + return v + if len(v) < 8: + raise ValueError('Password must be at least 8 characters long') + if not any(c.isupper() for c in v): + raise ValueError('Password must contain at least one uppercase letter') + if not any(c.islower() for c in v): + raise ValueError('Password must contain at least one lowercase letter') + if not any(c.isdigit() for c in v): + raise ValueError('Password must contain at least one digit') + if not any(c in "!@#$%^&*()_+-=[]{}|;:'\",.<>/?`~" for c in v): + raise ValueError('Password must contain at least one special character') + return v + +class UserUpdate(BaseModel): + username: Optional[str] = None + full_name: Optional[str] = None + profile_pic: Optional[str] = None + bio: Optional[str] = None + is_onboarded: Optional[bool] = None + interests: Optional[str] = None + referral_source: Optional[str] = None + goals: Optional[str] = None + show_wins: Optional[bool] = None + show_trophies: Optional[bool] = None + notif_new_follower: Optional[bool] = None + notif_challenge_win: Optional[bool] = None + notif_comments: Optional[bool] = None + notif_likes: Optional[bool] = None + email_weekly: Optional[bool] = None + email_challenges: Optional[bool] = None + email_payouts: Optional[bool] = None + email_marketing: Optional[bool] = None + payout_method: Optional[str] = None + two_factor_enabled: Optional[bool] = None + +class User(UserBase): + id: int + is_premium: bool + is_verified: bool + is_onboarded: bool + flash_uploads: int + home_uploads: int + flash_quota_limit: int + home_quota_limit: int + google_id: Optional[str] = None + bio: Optional[str] = None + role: str + public_key: Optional[str] = None + show_wins: Optional[bool] = True + show_trophies: Optional[bool] = True + notif_new_follower: Optional[bool] = True + notif_challenge_win: Optional[bool] = True + notif_comments: Optional[bool] = True + notif_likes: Optional[bool] = False + email_weekly: Optional[bool] = True + email_challenges: Optional[bool] = True + email_payouts: Optional[bool] = True + email_marketing: Optional[bool] = False + payout_method: Optional[str] = "stripe" + two_factor_enabled: Optional[bool] = False + +class EmailVerification(BaseModel): + email: str + code: str + +class ResendVerification(BaseModel): + email: str + +class PasswordChange(BaseModel): + current_password: str + new_password: str + +class VerificationResponse(BaseModel): + message: str + username: Optional[str] = None + email: Optional[str] = None + + model_config = ConfigDict(from_attributes=True) + +class SessionOut(BaseModel): + id: int + device_info: str + ip_address: str + last_active: datetime + is_current: bool = False + + model_config = ConfigDict(from_attributes=True) + +class UserProfile(User): + followers_count: int + following_count: int + total_views: int + total_likes: int = 0 + featured_video: Optional["Video"] = None + most_popular_video: Optional["Video"] = None + videos_count: int + flash_videos_count: int + posts_count: int + videos: List["Video"] + flash_videos: List["Video"] + posts: List["Post"] + liked_videos: List["Video"] = [] + trophies: List["ChallengeEntry"] = [] + is_following: bool = False + +class UserUpdateResponse(BaseModel): + user: User + access_token: Optional[str] = None + +class UserGoogleAuth(BaseModel): + credential: str + +class Token(BaseModel): + access_token: Optional[str] = None + token_type: Optional[str] = "bearer" + two_factor_required: bool = False + username: Optional[str] = None + methods: Optional[List[str]] = None + +class TokenData(BaseModel): + username: Optional[str] = None + code: Optional[str] = None + +class VideoBase(BaseModel): + title: str + description: Optional[str] = None + video_type: str + tags: Optional[str] = None + +class VideoCreate(VideoBase): + video_url: str + url_480p: Optional[str] = None + url_720p: Optional[str] = None + url_1080p: Optional[str] = None + url_2k: Optional[str] = None + url_4k: Optional[str] = None + thumbnail_url: str + duration: Optional[int] = 0 + processing_key: Optional[str] = None + processing_message: Optional[str] = None + description: Optional[str] = None + +class Video(VideoBase): + id: Union[int, str] + public_id: Optional[str] = None + video_url: str + url_480p: Optional[str] = None + url_720p: Optional[str] = None + url_1080p: Optional[str] = None + url_2k: Optional[str] = None + url_4k: Optional[str] = None + thumbnail_url: str + status: str + owner_id: int + owner: Optional[UserPublic] = None + views: int + earnings: float + shares: int = 0 + likes_count: int = 0 + comments_count: int = 0 + liked_by_user: bool = False + owner_followed: bool = False + duration: int = 0 + processing_key: Optional[str] = None + processing_message: Optional[str] = None + failed_at: Optional[datetime] = None + created_at: Optional[datetime] = None + + @field_validator('likes_count', 'comments_count', 'shares', mode='before') + @classmethod + def ensure_int(cls, v): + return v if v is not None else 0 + + @field_validator('video_url', 'thumbnail_url', 'url_480p', 'url_720p', 'url_1080p', 'url_2k', 'url_4k', mode='before') + @classmethod + def resolve_cdn_url(cls, v): + if not v or not isinstance(v, str): + return v + if "amazonaws.com" in v or "monteeq.s3" in v or "cdn.monteeq.com" in v: + try: + from app.core.storage import storage + if ".com/" in v: + parts = v.split(".com/") + if len(parts) > 1: + return storage.get_url(parts[1]) + except Exception: + return v + return v + + @field_serializer('id') + def serialize_id(self, v: int) -> Union[int, str]: + return self.public_id if (hasattr(self, 'public_id') and self.public_id) else v + + model_config = ConfigDict(from_attributes=True) + +class PostBase(BaseModel): + content: Optional[str] = None + image_url: Optional[str] = None + tags: Optional[str] = None + +class PostCreate(PostBase): + original_post_id: Optional[int] = None + +class Post(PostBase): + id: int + owner_id: int + owner: Optional[UserPublic] = None + created_at: Optional[datetime] = None + likes_count: int = 0 + comments_count: int = 0 + liked_by_user: bool = False + original_post_id: Optional[int] = None + original_post: Optional["Post"] = None + views_count: int = 0 + reposted_by: Optional[UserPublic] = None + + @field_validator('likes_count', 'comments_count', 'views_count', mode='before') + @classmethod + def ensure_int_post(cls, v): + return v if v is not None else 0 + + @field_validator('image_url', mode='before') + @classmethod + def resolve_post_cdn_url(cls, v): + if not v or not isinstance(v, str): + return v + if "amazonaws.com" in v or "monteeq.s3" in v or "cdn.monteeq.com" in v: + try: + from app.core.storage import storage + if ".com/" in v: + parts = v.split(".com/") + if len(parts) > 1: + return storage.get_url(parts[1]) + except Exception: + return v + return v + + model_config = ConfigDict(from_attributes=True) + +class AdBase(BaseModel): + title: str + image_url: str + is_active: bool + +class Ad(AdBase): + id: int + + model_config = ConfigDict(from_attributes=True) + +class CommentBase(BaseModel): + content: str + +class CommentCreate(CommentBase): + parent_id: Optional[int] = None + +class Comment(CommentBase): + id: int + video_id: Optional[int] = None + post_id: Optional[int] = None + parent_id: Optional[int] = None + owner_id: int + owner: Optional[UserPublic] = None + created_at: Optional[datetime] = None + likes_count: Optional[int] = 0 + is_liked: bool = False + replies: List["Comment"] = [] + + model_config = ConfigDict(from_attributes=True) + +class Achievement(BaseModel): + id: int + milestone_name: str + reached_at: datetime + + model_config = ConfigDict(from_attributes=True) + +class UnifiedSearchResponse(BaseModel): + videos: List[Video] + users: List[User] + posts: List[Post] + +class UserInsights(BaseModel): + total_views: int = 0 + total_likes: int = 0 + total_earnings: float = 0.0 + total_shares: int = 0 + home_videos: int = 0 + flash_videos: int = 0 + posts_count: int = 0 + followers: int = 0 + following: int = 0 + next_milestone: int = 0 + new_milestone_reached: Optional[str] = None + achievements: List[str] = [] + top_countries: List[dict] = [] # [{"country": "USA", "count": 100}, ...] + + @field_validator('total_views', 'total_likes', 'total_shares', 'home_videos', 'flash_videos', 'posts_count', 'followers', 'following', 'next_milestone', mode='before') + @classmethod + def ensure_int_insights(cls, v): + return v if v is not None else 0 + + @field_validator('total_earnings', mode='before') + @classmethod + def ensure_float_insights(cls, v): + return v if v is not None else 0.0 + + model_config = ConfigDict(from_attributes=True) + +class PerformanceDataPoint(BaseModel): + date: str + views: int + likes: int + followers: int + earnings: float + uploads: int + +class UserPerformance(BaseModel): + data: List[PerformanceDataPoint] + metric: str # views, likes, followers, earnings + +class ChatMessageBase(BaseModel): + encrypted_content: str + iv: str + recipient_key: str + sender_key: str + message_type: Optional[str] = "text" + attachment_url: Optional[str] = None + file_metadata: Optional[str] = None + +class ChatMessageCreate(ChatMessageBase): + recipient_username: str + +class ChatMessage(ChatMessageBase): + id: int + conversation_id: int + sender_id: int + created_at: datetime + + model_config = ConfigDict(from_attributes=True) + +class Conversation(BaseModel): + id: int + user1_id: int + user2_id: int + user1: UserPublic + user2: UserPublic + created_at: datetime + messages: List[ChatMessage] = [] + + model_config = ConfigDict(from_attributes=True) + +class KeyUpload(BaseModel): + public_key: str + +class PrekeyBundleUpload(BaseModel): + device_id: str + identity_key: str + signed_prekey: str + signature: str + one_time_prekeys: List[str] + +class PrekeyBundleOut(BaseModel): + user_id: int + device_id: str + identity_key: str + signed_prekey: str + signature: str + one_time_prekey: Optional[str] = None + + model_config = ConfigDict(from_attributes=True) + +class OneTimePrekeysUpload(BaseModel): + device_id: str + keys: List[str] + +class ChallengeBase(BaseModel): + title: str + description: str + brand: Optional[str] = None + prize: str + is_open: bool = True + is_paid: bool = False + is_gold: bool = False + entry_fee: float = 0.0 + start_date: Optional[datetime] = None + end_date: Optional[datetime] = None + +class ChallengeCreate(ChallengeBase): + pass + +class ChallengeEntryCreate(BaseModel): + video_id: int + +class ChallengeEntry(BaseModel): + id: int + challenge_id: int + user_id: int + video_id: int + is_winner: bool = False + created_at: datetime + user: Optional[UserPublic] = None + video: Optional[Video] = None + challenge: Optional["Challenge"] = None + + model_config = ConfigDict(from_attributes=True) + +class Challenge(ChallengeBase): + id: int + entry_count: int + winner_picked: bool = False + created_at: datetime + + model_config = ConfigDict(from_attributes=True) + +class ChallengeLeaderboardEntry(BaseModel): + username: str + profile_pic: Optional[str] = None + video_count: int = 0 # In case we want to show multiple entries, but requirement says "one video" + # For now, let's just return the ChallengeEntry details in the leaderboard + entry: ChallengeEntry + score: int # e.g., views or likes + +class TransactionBase(BaseModel): + amount: float + transaction_type: str + reference_id: Optional[str] = None + description: Optional[str] = None + +class Transaction(TransactionBase): + id: int + wallet_id: int + created_at: datetime + model_config = ConfigDict(from_attributes=True) + +class WalletBase(BaseModel): + balance: float + currency: str = "NGN" + +class Wallet(WalletBase): + id: int + user_id: int + created_at: datetime + updated_at: datetime + transactions: List[Transaction] = [] + model_config = ConfigDict(from_attributes=True) + + + +class PayoutRequestCreate(BaseModel): + amount: float + bank_details: Optional[str] = None # JSON: { bank, account_number, account_name } + +class PayoutRequestSchema(BaseModel): + id: int + user_id: int + wallet_id: int + amount: float + status: str + bank_details: Optional[str] = None + admin_note: Optional[str] = None + requested_at: datetime + processed_at: Optional[datetime] = None + user: Optional[UserPublic] = None + model_config = ConfigDict(from_attributes=True) + +class PaymentVerify(BaseModel): + reference: str + +class PaymentInitialize(BaseModel): + is_yearly: bool = False + +class PaymentInitializeResponse(BaseModel): + status: str + reference: str + checkout_url: Optional[str] = None + +class ProPricingResponse(BaseModel): + monthly_price: float + yearly_price: float + +class ProUpgradeResponse(BaseModel): + status: str + message: str + is_premium: bool + +class SubscriptionCreateRequest(BaseModel): + is_yearly: bool = False + full_name: str + billing_email: str + billing_country: str + billing_zip: str + +class SubscriptionCreateResponse(BaseModel): + status: str + subscriptionId: str + clientSecret: str + +class SubscriptionVerifyRequest(BaseModel): + subscription_id: str + +class SubscriptionStatusResponse(BaseModel): + status: str + tier: str + current_period_end: Optional[datetime] = None + stripe_customer_id: Optional[str] = None + cancel_at_period_end: Optional[bool] = False + +class SubscriptionAutoRenewRequest(BaseModel): + auto_renew: bool + +class CustomerPortalResponse(BaseModel): + url: str + +class ContentAnalyticsItem(BaseModel): + id: int + title: str + video_type: str + views: int + likes_count: int + shares: int + engagement_rate: float # (likes + shares) / views * 100 + + model_config = ConfigDict(from_attributes=True) + +class AudienceSplit(BaseModel): + returning_viewers: int + new_viewers: int + total_views: int + +class ScoreBreakdown(BaseModel): + consistency: int # 0-100: how regularly they post + engagement: int # 0-100: (likes+shares) / views + retention: int # 0-100: returning viewers % + frequency: int # 0-100: total approved video count + +class GrowthIntelligence(BaseModel): + score: int # 0-100 composite + breakdown: ScoreBreakdown + insights: List[str] # plain text, HTML-safe + +class AttachmentResponse(BaseModel): + url: str + filename: Optional[str] = None + +class PasswordReset(BaseModel): + email: str + code: str + new_password: str + + @field_validator('new_password') + @classmethod + def password_complexity_reset(cls, v: str) -> str: + if len(v) < 8: + raise ValueError('Password must be at least 8 characters long') + if not any(c.isupper() for c in v): + raise ValueError('Password must contain at least one uppercase letter') + if not any(c.islower() for c in v): + raise ValueError('Password must contain at least one lowercase letter') + if not any(c.isdigit() for c in v): + raise ValueError('Password must contain at least one digit') + if not any(c in "!@#$%^&*()_+-=[]{}|;:'\",.<>/?`~" for c in v): + raise ValueError('Password must contain at least one special character') + return v + +class GoogleLinkRequest(BaseModel): + id_token: str + +class PartnerLeadBase(BaseModel): + brand_name: str + contact_email: str + campaign_type: str + details: str + +class PartnerLeadCreate(PartnerLeadBase): + pass + +class PartnerLead(PartnerLeadBase): + id: int + status: str + created_at: datetime + + model_config = ConfigDict(from_attributes=True) + + +class DiscoveredCategoryOut(BaseModel): + id: int + name: str + display_name: str + count: int + is_approved: bool + related_tags: Optional[str] = "" + icon_hint: Optional[str] = None + + model_config = ConfigDict(from_attributes=True) +class Follow(BaseModel): + id: int + follower_id: int + following_id: int + created_at: datetime + + model_config = ConfigDict(from_attributes=True) + +class FollowingFeedItem(BaseModel): + type: str # 'video', 'flash', 'post' + data: Union[Video, Post] + created_at: datetime diff --git a/app/services/category_service.py b/app/services/category_service.py new file mode 100644 index 0000000000000000000000000000000000000000..0eac0816596ec3b9521c4ab41c3698a855702727 --- /dev/null +++ b/app/services/category_service.py @@ -0,0 +1,249 @@ +""" +category_service.py +─────────────────── +Intelligent category discovery engine. + +Scans video hashtags, vets them for "meaningfulness", and manages +the DiscoveredCategory table. Supports semantic tag expansion so +that browsing a category shows related content, not just exact matches. +""" + +import logging +import re +from collections import Counter +from typing import Dict, List, Optional, Set + +from sqlalchemy import or_ +from sqlalchemy.orm import Session, joinedload + +from app.db.utils import sync_pk_sequence +from app.models.models import DiscoveredCategory, Video + +log = logging.getLogger("monteeq.categories") + +# ─── Vetting rules ──────────────────────────────────────────────────────────── + +# Words that are too generic to be a meaningful category +STOP_WORDS: Set[str] = { + "video", "clip", "post", "content", "edit", "edits", "new", "best", + "top", "shorts", "short", "reel", "reels", "viral", "trending", + "fyp", "foryou", "foryoupage", "fy", "fypシ", "for", "you", "page", + "like", "follow", "share", "subscribe", "comment", "watch", "hot", + "fire", "lit", "cap", "no", "yes", "lol", "omg", "wow", "the", + "monteeq", "flash", "home", "challenge", "entry", "test", "demo", +} + +# Minimum tag frequency to even be considered +MIN_FREQUENCY = 2 + +# Minimum tag length (characters) +MIN_LENGTH = 3 + + +def _is_meaningful(tag: str) -> bool: + """ + Vet a tag for meaningfulness. + Rules: + - Must be >= MIN_LENGTH characters + - Must NOT contain any digit + - Must NOT be a stop-word + - Must be purely alphabetic (allows hyphens for compound words) + """ + if len(tag) < MIN_LENGTH: + return False + + # Reject any tag containing digits + if any(c.isdigit() for c in tag): + return False + + # Reject stop-words + if tag in STOP_WORDS: + return False + + # Must be alphabetic (allow hyphens for compound words like "hip-hop") + if not re.match(r'^[a-z]+(-[a-z]+)*$', tag): + return False + + return True + + +# ─── Semantic similarity map ───────────────────────────────────────────────── +# This maps a canonical category to related tags. +# When a user browses "football", the feed will include videos tagged with +# any of these related terms. + +SEMANTIC_MAP: Dict[str, List[str]] = { + "football": ["soccer", "goal", "penalty", "freekick", "messi", "ronaldo", "neymar", "haaland", "premier", "laliga", "ucl", "worldcup", "striker", "goalkeeper"], + "anime": ["manga", "otaku", "naruto", "onepiece", "dragonball", "jujutsu", "demonslayer", "aot", "bleach", "goku", "luffy", "sasuke"], + "gaming": ["gamer", "gameplay", "esports", "valorant", "fortnite", "minecraft", "cod", "warzone", "apex", "league", "roblox", "pubg", "overwatch"], + "amv": ["animeedit", "amvedit", "animemv", "musicvideo"], + "music": ["song", "beat", "hiphop", "rap", "rnb", "afrobeats", "pop", "rock", "jazz", "drill", "trap", "producer"], + "comedy": ["funny", "humor", "meme", "memes", "joke", "jokes", "skit", "skits", "prank", "pranks"], + "fitness": ["gym", "workout", "exercise", "bodybuilding", "muscle", "gains", "cardio", "crossfit", "yoga"], + "cooking": ["food", "recipe", "chef", "kitchen", "baking", "meal", "cuisine"], + "fashion": ["style", "outfit", "streetwear", "drip", "clothes", "sneakers", "designer"], + "art": ["drawing", "painting", "illustration", "sketch", "digital", "artist", "creative"], + "dance": ["dancing", "choreography", "dancer", "hiphop", "breaking", "twerk"], + "basketball": ["nba", "hoops", "dunk", "lebron", "curry", "jordan"], + "boxing": ["fighter", "knockout", "mma", "ufc", "sparring", "tyson"], + "cars": ["automotive", "drift", "racing", "supercar", "jdm", "tuning", "motorsport"], + "nature": ["wildlife", "landscape", "ocean", "mountain", "sunset", "travel"], + "tech": ["technology", "coding", "programming", "gadget", "software", "hardware", "ai"], + "motivation": ["motivational", "grind", "hustle", "mindset", "success", "inspire", "discipline"], + "education": ["learning", "study", "tutorial", "howto", "science", "history", "math"], +} + +# Build reverse lookup: tag -> canonical category +_REVERSE_MAP: Dict[str, str] = {} +for canonical, related in SEMANTIC_MAP.items(): + for tag in related: + _REVERSE_MAP[tag] = canonical + + +def get_canonical_category(tag: str) -> Optional[str]: + """If a tag is a known alias, return its canonical category name.""" + return _REVERSE_MAP.get(tag) + + +def get_expanded_tags(category_name: str) -> List[str]: + """ + Given a category name, return all tags that should match + (the category itself + its related tags from the semantic map + + any related_tags stored in the DB entry). + """ + tags = [category_name] + if category_name in SEMANTIC_MAP: + tags.extend(SEMANTIC_MAP[category_name]) + return list(set(tags)) + + +# ─── Discovery engine ───────────────────────────────────────────────────────── + +def discover_categories(db: Session) -> List[DiscoveredCategory]: + """ + Scan all approved videos, aggregate tags, vet for meaningfulness, + and upsert into the DiscoveredCategory table. + + Returns newly discovered (but not yet approved) categories. + """ + # 1. Fetch all tags from approved videos + videos = db.query(Video.tags).filter( + Video.status == "approved", + Video.tags.isnot(None), + Video.tags != "", + ).all() + + # 2. Aggregate tag frequencies + tag_counter: Counter = Counter() + for (tags_str,) in videos: + for raw_tag in tags_str.split(","): + tag = raw_tag.strip().lower() + if tag: + tag_counter[tag] += 1 + + # 3. Vet and upsert + existing_by_name = {c.name: c for c in db.query(DiscoveredCategory).all()} + new_categories = [] + for tag, count in tag_counter.items(): + if count < MIN_FREQUENCY: + continue + + if not _is_meaningful(tag): + continue + + # Check if a known alias → merge into canonical + canonical = get_canonical_category(tag) + effective_name = canonical if canonical else tag + + existing = existing_by_name.get(effective_name) + + if existing: + existing.count = count + # If this tag is an alias, make sure the canonical entry + # has it in related_tags + if canonical and tag != canonical: + current_related = set( + t.strip() for t in (existing.related_tags or "").split(",") if t.strip() + ) + current_related.add(tag) + existing.related_tags = ",".join(sorted(current_related)) + else: + # Build related tags from semantic map + related = SEMANTIC_MAP.get(effective_name, []) + # Auto-approve if it's in our semantic map (known good category) + is_known = effective_name in SEMANTIC_MAP + + cat = DiscoveredCategory( + name=effective_name, + display_name=effective_name.replace("-", " ").title(), + count=count, + is_approved=is_known, # Auto-approve known categories + related_tags=",".join(related), + ) + db.add(cat) + existing_by_name[effective_name] = cat + new_categories.append(cat) + + sync_pk_sequence(db, "discovered_categories") + db.commit() + + log.info( + "[categories] Discovery complete: %d total tags, %d meaningful, %d new", + len(tag_counter), sum(1 for t in tag_counter if _is_meaningful(t)), len(new_categories), + ) + return new_categories + + +def get_approved_categories(db: Session) -> List[DiscoveredCategory]: + """Return all approved categories ordered by popularity.""" + return ( + db.query(DiscoveredCategory) + .filter(DiscoveredCategory.is_approved == True) + .order_by(DiscoveredCategory.count.desc()) + .all() + ) + + +def get_videos_for_category( + db: Session, + category_name: str, + video_type: str = "flash", + limit: int = 30, +) -> List[Video]: + """ + Fetch videos matching a category using semantic tag expansion. + This returns videos that have the exact tag OR any related tags, + providing a rich and varied feed. + """ + # Look up the category for its stored related_tags + category = db.query(DiscoveredCategory).filter( + DiscoveredCategory.name == category_name, + DiscoveredCategory.is_approved == True, + ).first() + + # Build the full set of tags to search for + search_tags = get_expanded_tags(category_name) + + # Add any DB-stored related tags + if category and category.related_tags: + db_related = [t.strip() for t in category.related_tags.split(",") if t.strip()] + search_tags.extend(db_related) + search_tags = list(set(search_tags)) + + # Build OR conditions for each tag using LIKE + tag_conditions = [Video.tags.ilike(f"%{tag}%") for tag in search_tags] + + videos = ( + db.query(Video) + .options(joinedload(Video.owner)) + .filter( + Video.video_type == video_type, + Video.status == "approved", + or_(*tag_conditions), + ) + .order_by(Video.discovery_score.desc()) + .limit(limit) + .all() + ) + + return videos diff --git a/app/services/challenge_service.py b/app/services/challenge_service.py new file mode 100644 index 0000000000000000000000000000000000000000..4901997fb1c8361fb770ac721ecff522b6c6e88d --- /dev/null +++ b/app/services/challenge_service.py @@ -0,0 +1,37 @@ +from sqlalchemy.orm import Session +from sqlalchemy import func +from app.models.models import Challenge, ChallengeEntry, Video +from datetime import datetime + +def resolve_expired_challenges(db: Session): + """ + Finds challenges that have reached their end_date but haven't had a winner picked. + Selects the entry with the highest view count as the winner. + """ + now = datetime.now() + + # 1. Find expired challenges without winners + expired_challenges = db.query(Challenge).filter( + Challenge.end_date <= now, + Challenge.winner_picked == False + ).all() + + for challenge in expired_challenges: + # 2. Find the entry with the highest view count + # Join ChallengeEntry with Video to get view counts + winner_entry = db.query(ChallengeEntry).join(Video).filter( + ChallengeEntry.challenge_id == challenge.id + ).order_by(Video.views.desc()).first() + + if winner_entry: + # 3. Mark as winner + winner_entry.is_winner = True + challenge.winner_picked = True + + # Optional: Notify the user they won (can integrate notification service here) + + db.commit() + db.refresh(winner_entry) + db.refresh(challenge) + + return len(expired_challenges) diff --git a/app/services/email_service.py b/app/services/email_service.py new file mode 100644 index 0000000000000000000000000000000000000000..7b88a671fda25e5a85c9ec6695f91e590dee297d --- /dev/null +++ b/app/services/email_service.py @@ -0,0 +1,908 @@ +""" +Email service for Monteeq platform. +Uses Zoho SMTP for all communications. +""" +import logging +import os +import random +import requests +import smtplib +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from tenacity import retry, stop_after_attempt, wait_exponential + +from app.core import config +from app.core.config import SMTP_FROM, SMTP_FROM_NAME +from app.email_templates import pick +from app.email_templates import verification as _t_verify +from app.email_templates import password_reset as _t_reset +from app.email_templates import pro_upgrade as _t_pro +from app.email_templates import challenge_announce as _t_announce +from app.email_templates import challenge_exit as _t_exit +from app.email_templates import welcome as _t_welcome +from app.email_templates import day3_nudge as _t_day3 +from app.email_templates import first_video as _t_fvideo +from app.email_templates import first_follower as _t_ffollower +from app.email_templates import first_like as _t_flike +from app.email_templates import digest as _t_digest +from app.email_templates import reengagement as _t_reeng +from app.email_templates import challenge_ending as _t_ending +from app.email_templates import challenge_result as _t_result +from app.email_templates import security as _t_sec +from app.email_templates import subscription as _t_sub +from app.email_templates import first_comment as _t_fcomment +from app.email_templates import mention as _t_mention +from app.email_templates import growth_drip as _t_gdrip +from app.email_templates import celebration as _t_celeb +from app.email_templates import social_batch as _t_sbatch + +logger = logging.getLogger(__name__) + +@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10)) +def _execute_smtp_send(to_email, all_recipients, msg_string, is_bcc): + """Executes the SMTP send with automatic retries on failure.""" + if config.SMTP_PORT == 465: + smtp_cls = smtplib.SMTP_SSL + use_starttls = False + else: + smtp_cls = smtplib.SMTP + use_starttls = True + + with smtp_cls(config.SMTP_HOST, config.SMTP_PORT, timeout=15) as server: + if use_starttls: + server.starttls() + server.login(config.SMTP_USER, config.SMTP_PASS) + + if is_bcc: + server.sendmail(config.SMTP_FROM, all_recipients, msg_string) + else: + server.sendmail(config.SMTP_FROM, to_email, msg_string) + +def _send_email_logic(to_email: str, subject: str, plain_text: str, html_content: str, bcc_list: list = None) -> bool: + """ + Core logic to send emails via Zoho SMTP. + """ + # --- 1. Try Zoho SMTP --- + if config.SMTP_HOST and config.SMTP_USER and config.SMTP_PASS: + try: + msg = MIMEMultipart("alternative") + msg["Subject"] = subject + msg["From"] = f"{config.SMTP_FROM_NAME} <{config.SMTP_FROM}>" + + if bcc_list: + # For mass emails via SMTP, we send one by one or use BCC header. + # To protect privacy, we'll send to sender and BCC others. + msg["To"] = "undisclosed-recipients:;" + all_recipients = [to_email] + bcc_list if to_email else bcc_list + else: + msg["To"] = to_email + all_recipients = [to_email] + + msg.attach(MIMEText(plain_text, "plain")) + msg.attach(MIMEText(html_content, "html")) + + _execute_smtp_send(to_email, all_recipients, msg.as_string(), bool(bcc_list)) + + logger.info(f"SMTP: Email '{subject}' sent to {to_email}") + return True + except Exception as e: + logger.error( + f"SMTP Failed for {to_email} after retries using " + f"{config.SMTP_HOST}:{config.SMTP_PORT} " + f"as {config.SMTP_USER} — {type(e).__name__}: {e}" + ) + logger.warning(f"Falling back to console log for email to {to_email}") + + # --- 2. Final Fallback (Console) --- + logger.warning(f"NO EMAIL SERVICE ACTIVE. Email '{subject}' to {to_email}") + print(f"\n[DEV LOG] EMAIL TO {to_email}\nSUBJECT: {subject}\nCONTENT: {plain_text}\n") + return False + +def _base_email_template(content_html: str) -> str: + """Wraps inner content in the Monteeq Gilded Obsidian base email shell.""" + return f""" + + + + + + + + Monteeq + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +""" + + +def _primary_button(text: str, url: str) -> str: + """Helper to generate an Outlook-compatible primary button.""" + return f""" + + + {text} + + """ + + +def send_verification_email(to_email: str, code: str) -> bool: + _v = pick(_t_verify.VARIANTS) + plain_text = f"Welcome to Monteeq!\n\nYour verification code is: {code}\nExpires in 10 mins." + content_html = f""" +

{_v['heading']}

+

{_v['body']}

+ + + + + + +
+ {code} +
+ +

{_v['caption']}

+""" + html = _base_email_template(content_html) + return _send_email_logic(to_email, f"{code} is your Monteeq code", plain_text, html) + +def send_password_reset_email(to_email: str, token: str) -> bool: + reset_link = f"{config.FRONTEND_URL}/reset-password?token={token}&email={to_email}" + plain_text = f"Reset your Monteeq password:\n\nClick here: {reset_link}\n\nThis link expires in 1 hour." + _v = pick(_t_reset.VARIANTS) + content_html = f""" +

{_v['heading']}

+

{_v['body']}

+ + + + +
+ {_primary_button("Reset Password", reset_link)} +
+ + + + + + +
+

+ {_v['security_note']} +

+
+""" + html = _base_email_template(content_html) + return _send_email_logic(to_email, _v.get("subject", "Reset your Monteeq password"), plain_text, html) + +def send_challenge_announcement_batch(bcc_emails: list, title: str, prize: str, end_date: str) -> bool: + _v = pick(_t_announce.VARIANTS) + content_html = f""" +

{_v['eyebrow']}

+

{title}

+ + + + + + +
+

+ Prize Pool +

+

+ {prize} +

+
+ +

+ {_v['body'].format(title=title, prize=prize, end_date=end_date)} +

+ + + +
+ {_primary_button("Enter Challenge", "https://monteeq.com/challenges")} +
+""" + html = _base_email_template(content_html) + plain_text = f"New Challenge: {title}! Win {prize}. Join at https://monteeq.com/challenges" + return _send_email_logic(None, _v['subject'].format(title=title, prize=prize), plain_text, html, bcc_list=bcc_emails) + +def send_pro_upgrade_email(to_email: str, username: str) -> bool: + _v = pick(_t_pro.VARIANTS) + _heading = _v['heading'].format(username=username) + _body = _v['body'].format(username=username) + content_html = f""" +

{_heading}

+

+ {_body} +

+ + + + + + + +
+ ✓  + 4K Video Uploads +
+ ✓  + Priority Processing Queue +
+ ✓  + Advanced Creator Analytics +
+ ✓  + Ad-Free Experience +
+ + + +
+ {_primary_button("Start Creating", "https://monteeq.com")} +
+""" + html = _base_email_template(content_html) + plain_text = f"Congratulations {username}! You are now a Monteeq Pro user." + return _send_email_logic(to_email, _v['subject'].format(username=username), plain_text, html) + +def send_challenge_exit_email(to_email: str, username: str, challenge_title: str) -> bool: + _v = pick(_t_exit.VARIANTS) + _heading = _v['heading'].format(username=username, challenge_title=challenge_title) + _body = _v['body'].format(username=username, challenge_title=challenge_title) + _followup = _v['followup'].format(username=username, challenge_title=challenge_title) + content_html = f""" +

{_heading}

+

+ {_body} +

+ + + + + + +
+

+ {challenge_title} +

+
+ +

+ {_followup} +

+ + + +
+ + View Challenges + +
+""" + html = _base_email_template(content_html) + plain_text = f"Hi {username}, you've been removed from '{challenge_title}' because your entry video was deleted." + return _send_email_logic(to_email, f"Update on Challenge: {challenge_title}", plain_text, html) + +def send_email(to_email: str, subject: str, title: str, message: str, action_text: str = None, action_url: str = None) -> bool: + action_html = "" + if action_text and action_url: + full_url = f"{config.BASE_URL}{action_url}" if action_url.startswith("/") else action_url + action_html = f''' + + +
+ {_primary_button(action_text, full_url)} +
''' + + content_html = f""" +

{title}

+

{message}

+ {action_html} +""" + html_content = _base_email_template(content_html) + + return _send_email_logic(to_email, subject, message, html_content) + +# ── Shared style shortcuts ──────────────────────────────────────────────────── +_H = "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;font-size:24px;font-weight:800;color:#ffffff;margin:0 0 16px;line-height:1.3;" +_B = "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;font-size:15px;font-weight:400;color:#8e8e93;margin:0 0 16px;line-height:1.7;" +_S = "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;font-size:12px;color:#48484a;margin:0;line-height:1.6;" +_FF = "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;" + + +# ── 1. Welcome (Sign up) ────────────────────────────────────────────────────── +def send_welcome_email(to_email: str, username: str) -> bool: + _v = pick(_t_welcome.VARIANTS) + _heading = _v['heading'].format(username=username) + _body = _v['body'].format(username=username) + content_html = f""" +

{_heading}

+

{_body}

+ + + + + +
+ 01   + Upload your first video +
+ 02   + Complete your creator profile +
+ 03   + Explore the community feed +
+ + + +
{_primary_button("Upload Your First Video", "https://monteeq.com/upload")}
+""" + html = _base_email_template(content_html) + plain = f"Welcome to Monteeq, {username}! Upload your first video at https://monteeq.com/upload" + return _send_email_logic(to_email, f"Welcome to Monteeq, {username}", plain, html) + + +# ── 2. Day-3 onboarding nudge ───────────────────────────────────────────────── +def send_day3_nudge_email(to_email: str, username: str) -> bool: + _v = pick(_t_day3.VARIANTS) + _heading = _v['heading'].format(username=username) + _body = _v['body'].format(username=username) + content_html = f""" +

{_heading}

+

{_body}

+ + +
{_primary_button("Upload a Video", "https://monteeq.com/upload")}
+

Takes less than 2 minutes.

+""" + html = _base_email_template(content_html) + plain = f"Hey {username}, upload your first video at https://monteeq.com/upload" + return _send_email_logic(to_email, _v['subject'].format(username=username), plain, html) + + +# ── 3. First video uploaded (milestone) ────────────────────────────────────── +def send_first_video_email(to_email: str, username: str, video_title: str, video_url: str) -> bool: + _v = pick(_t_fvideo.VARIANTS) + _heading = _v['heading'].format(username=username, video_title=video_title) + _body = _v['body'].format(username=username, video_title=video_title) + _tip = _v['tip'].format(username=username, video_title=video_title) + content_html = f""" +

{_heading}

+

{_body}

+ + + +
+

What to do next

+

+ {_tip} +

+
+ + + +
{_primary_button("View Your Video", video_url)}
+""" + html = _base_email_template(content_html) + plain = f"Your video '{video_title}' is live on Monteeq. View it at {video_url}" + return _send_email_logic(to_email, _v['subject'].format(username=username, video_title=video_title), plain, html) + + +# ── 4. First follower (social) ──────────────────────────────────────────────── +def send_first_follower_email(to_email: str, username: str, follower_name: str) -> bool: + _v = pick(_t_ffollower.VARIANTS) + _heading = _v['heading'].format(username=username, follower_name=follower_name) + _body = _v['body'].format(username=username, follower_name=follower_name) + content_html = f""" +

{_heading}

+

{_body}

+ + +
{_primary_button("See Your Profile", f"https://monteeq.com/u/{username}")}
+""" + html = _base_email_template(content_html) + plain = f"{follower_name} just followed you on Monteeq." + return _send_email_logic(to_email, _v['subject'].format(username=username, follower_name=follower_name), plain, html) + + +# ── 5. First like (social) ──────────────────────────────────────────────────── +def send_first_like_email(to_email: str, username: str, video_title: str, liker_name: str, video_url: str) -> bool: + _v = pick(_t_flike.VARIANTS) + _heading = _v['heading'].format(username=username, video_title=video_title, liker_name=liker_name) + _body = _v['body'].format(username=username, video_title=video_title, liker_name=liker_name) + content_html = f""" +

{_heading}

+

{_body}

+ + +
{_primary_button("View Your Video", video_url)}
+""" + html = _base_email_template(content_html) + plain = f"{liker_name} liked your video '{video_title}'." + return _send_email_logic(to_email, _v['subject'].format(username=username, video_title=video_title, liker_name=liker_name), plain, html) + + +# ── 6. Weekly digest (batch) ────────────────────────────────────────────────── +def send_weekly_digest_email(bcc_emails: list, videos: list) -> bool: + """videos: list of dicts with keys: title, creator, url""" + _v = pick(_t_digest.WEEKLY_VARIANTS) + rows_html = "" + for i, v in enumerate(videos[:5]): + border = "border-bottom:1px solid #2e2e2e;" if i < len(videos[:5]) - 1 else "" + rows_html += f""" + + + {v.get('title','Untitled')} + + {v.get('creator','')} + """ + + content_html = f""" +

{_v['heading']}

+

{_v['body']}

+ + + {rows_html} +
+ + + +
{_primary_button("Open Your Feed", "https://monteeq.com")}
+""" + html = _base_email_template(content_html) + plain = "This week's top videos on Monteeq — https://monteeq.com" + return _send_email_logic(None, _v['subject'], plain, html, bcc_list=bcc_emails) + + +# ── 7. Monthly stats digest ─────────────────────────────────────────────────── +def send_monthly_stats_email(to_email: str, username: str, month: str, stats: dict) -> bool: + """stats: dict with keys: views, likes, followers, uploads""" + _v = pick(_t_digest.MONTHLY_VARIANTS) + _heading = _v['heading'].format(username=username, month=month) + _body = _v['body'].format(username=username, month=month) + def stat_cell(label, value): + return f""" +

{value}

+

{label}

+ """ + + content_html = f""" +

{_heading}

+

{_body}

+ + + + {stat_cell("Views", stats.get("views", 0))} + + {stat_cell("Likes", stats.get("likes", 0))} + + + + {stat_cell("New Followers", stats.get("followers", 0))} + + {stat_cell("Uploads", stats.get("uploads", 0))} + +
 
 
 
+ + + +
{_primary_button("View Full Analytics", "https://monteeq.com/analytics")}
+""" + html = _base_email_template(content_html) + plain = f"{username}'s {month} on Monteeq — {stats.get('views',0)} views, {stats.get('likes',0)} likes." + return _send_email_logic(to_email, _v['subject'].format(username=username, month=month), plain, html) + + +# ── 8. Re-engagement (30 days inactive) ────────────────────────────────────── +def send_reengagement_email(to_email: str, username: str, inactive_days: int = 30) -> bool: + _v = _t_reeng.pick_reengagement(inactive_days) + _heading = _v['heading'].format(username=username) + _body_1 = _v['body_1'].format(username=username) + _body_2 = _v['body_2'].format(username=username) + content_html = f""" +

{_heading}

+

{_body_1}

+

{_body_2}

+ + + +
{_primary_button("Upload a Video", "https://monteeq.com/upload")}
+ + +
+ + Or just browse the feed + +
+""" + html = _base_email_template(content_html) + plain = f"Hey {username}, we haven't seen you in {inactive_days} days. Come back to Monteeq: https://monteeq.com" + return _send_email_logic(to_email, _v['subject'].format(username=username), plain, html) + + +# ── 9. Challenge ending soon (campaign, batch) ──────────────────────────────── +def send_challenge_ending_soon_email(bcc_emails: list, title: str, prize: str, end_date: str) -> bool: + _v = pick(_t_ending.VARIANTS) + content_html = f""" +

{_v['eyebrow']}

+

{title}

+ + + +
+

+ Prize Pool +

+

{prize}

+

+ Closes {end_date} +

+
+ +

{_v['body'].format(title=title, prize=prize, end_date=end_date)}

+ + +
{_primary_button("Enter Now", "https://monteeq.com/challenges")}
+""" + html = _base_email_template(content_html) + plain = f"Last chance to enter {title} — prize: {prize}. Closes {end_date}. Enter at https://monteeq.com/challenges" + return _send_email_logic(None, _v['subject'].format(title=title, prize=prize, end_date=end_date), plain, html, bcc_list=bcc_emails) + + +# ── 10. Challenge result / winner announcement (batch) ─────────────────────── +def send_challenge_result_email(bcc_emails: list, challenge_title: str, winner_name: str, + winner_video_url: str, prize: str) -> bool: + _v = pick(_t_result.VARIANTS) + _eyebrow = _v['eyebrow'].format(challenge_title=challenge_title, winner_name=winner_name, prize=prize) + _heading = _v['heading'].format(challenge_title=challenge_title, winner_name=winner_name, prize=prize) + _body = _v['body'].format(challenge_title=challenge_title, winner_name=winner_name, prize=prize) + content_html = f""" +

{_eyebrow}

+

{_heading}

+ + + +
+

Winner

+

{winner_name}

+

Took home {prize}

+
+ +

+ {_body} +

+ + +
{_primary_button("Watch the Winning Edit", winner_video_url)}
+ + +
+ + More challenges are open + +
+""" + html = _base_email_template(content_html) + plain = f"{winner_name} won {challenge_title} and took home {prize}. Watch at {winner_video_url}" + return _send_email_logic(None, _v['subject'].format(challenge_title=challenge_title, winner_name=winner_name, prize=prize), plain, html, bcc_list=bcc_emails) + + +def send_security_email(to_email: str, template_type: str, username: str, **kwargs) -> bool: + _v = _t_sec.pick_security(template_type) + subject = _v['subject'].format(username=username, **kwargs) + heading = _v['heading'].format(username=username, **kwargs) + body = _v['body'].format(username=username, **kwargs) + action_text = _v.get('action_text', 'Secure Account') + body_html = body.replace('\n', '
') + content_html = f""" +

{heading}

+

{body_html}

+ + + +
{_primary_button(action_text, "https://monteeq.com/settings/security")}
+""" + html = _base_email_template(content_html) + plain = f"{heading}\n\n{body}" + return _send_email_logic(to_email, subject, plain, html) + + +def send_subscription_email(to_email: str, template_type: str, username: str, **kwargs) -> bool: + _v = _t_sub.pick_subscription(template_type) + subject = _v['subject'].format(username=username, **kwargs) + heading = _v['heading'].format(username=username, **kwargs) + body = _v['body'].format(username=username, **kwargs) + action_text = _v.get('action_text', 'Learn More') + body_html = body.replace('\n', '
') + content_html = f""" +

{heading}

+

{body_html}

+ + + +
{_primary_button(action_text, "https://monteeq.com/pro")}
+""" + html = _base_email_template(content_html) + plain = f"{heading}\n\n{body}" + return _send_email_logic(to_email, subject, plain, html) + + +def send_first_comment_email(to_email: str, username: str, video_title: str, commenter_name: str, comment_content: str, video_url: str) -> bool: + _v = pick(_t_fcomment.VARIANTS) + fmt = { + "username": username, + "video_title": video_title, + "commenter_name": commenter_name, + "comment_content": comment_content, + } + subject = _v['subject'].format(**fmt) + heading = _v['heading'].format(**fmt) + body = _v['body'].format(**fmt) + action_text = _v.get('action_text', 'View Comment') + body_html = body.replace('\n', '
') + content_html = f""" +

{heading}

+

{body_html}

+ + + +
{_primary_button(action_text, video_url)}
+""" + html = _base_email_template(content_html) + plain = f"{heading}\n\n{body}" + return _send_email_logic(to_email, subject, plain, html) + + +def send_mention_email(to_email: str, username: str, mentioner_name: str, context_text: str, action_url: str) -> bool: + _v = pick(_t_mention.VARIANTS) + fmt = { + "username": username, + "mentioner_name": mentioner_name, + "context_text": context_text, + } + subject = _v['subject'].format(**fmt) + heading = _v['heading'].format(**fmt) + body = _v['body'].format(**fmt) + action_text = _v.get('action_text', 'View Mention') + body_html = body.replace('\n', '
') + content_html = f""" +

{heading}

+

{body_html}

+ + + +
{_primary_button(action_text, action_url)}
+""" + html = _base_email_template(content_html) + plain = f"{heading}\n\n{body}" + return _send_email_logic(to_email, subject, plain, html) + + + +def send_growth_drip_email(to_email: str, username: str, week: int) -> bool: + _v = _t_gdrip.pick_growth_drip(week) + subject = _v['subject'].format(username=username) + heading = _v['heading'].format(username=username) + body = _v['body'].format(username=username) + action_text = _v.get('action_text', 'Learn More') + body_html = body.replace('\n', '
') + content_html = f""" +

{heading}

+

{body_html}

+ + + +
{_primary_button(action_text, "https://monteeq.com/settings/profile")}
+""" + html = _base_email_template(content_html) + plain = f"{heading}\n\n{body}" + return _send_email_logic(to_email, subject, plain, html) + + +def send_celebration_email(to_email: str, username: str, template_type: str, **kwargs) -> bool: + _v = _t_celeb.pick_celebration(template_type) + subject = _v['subject'].format(username=username, **kwargs) + heading = _v['heading'].format(username=username, **kwargs) + body = _v['body'].format(username=username, **kwargs) + action_text = _v.get('action_text', 'View Milestone') + body_html = body.replace('\n', '
') + content_html = f""" +

{heading}

+

{body_html}

+ + + +
{_primary_button(action_text, "https://monteeq.com")}
+""" + html = _base_email_template(content_html) + plain = f"{heading}\n\n{body}" + return _send_email_logic(to_email, subject, plain, html) + + +def send_social_batch_email(to_email: str, username: str, summary_text: str) -> bool: + _v = _t_sbatch.pick_social_batch() + subject = _v['subject'].format(username=username) + heading = _v['heading'].format(username=username) + body = _v['body'].format(username=username, summary_text=summary_text) + action_text = _v.get('action_text', 'View Notifications') + body_html = body.replace('\n', '
') + content_html = f""" +

{heading}

+

{body_html}

+ + + +
{_primary_button(action_text, "https://monteeq.com/notifications")}
+""" + html = _base_email_template(content_html) + plain = f"{heading}\n\n{body}" + return _send_email_logic(to_email, subject, plain, html) + + +_missing = [v for v, k in { + "SMTP_HOST": config.SMTP_HOST, + "SMTP_USER": config.SMTP_USER, + "SMTP_PASS": config.SMTP_PASS, + "SMTP_FROM": config.SMTP_FROM, +}.items() if not k] + +if _missing: + logger.warning( + f"EMAIL SERVICE MISCONFIGURED — missing env vars: {{', '.join(_missing)}}. " + "All emails will fall back to console logging until this is fixed." + ) diff --git a/app/services/email_trigger.py b/app/services/email_trigger.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c1c65c4c830b9329bc7778a35ddfb8602b33bc --- /dev/null +++ b/app/services/email_trigger.py @@ -0,0 +1,309 @@ +""" +email_trigger.py — Monteeq Email Automation Engine + +Central service that all API routes and Celery tasks call to send emails. +Enforces: + - Per-template cooldowns + - Daily / weekly send caps + - User preference checks + - Deduplication logging (EmailLog) + +Usage: + from app.services.email_trigger import EmailTrigger + EmailTrigger(db).welcome(user) + EmailTrigger(db).first_like(user, liker, video) +""" + +import logging +from datetime import datetime, timedelta, timezone +from contextlib import contextmanager + +from sqlalchemy.orm import Session + +from app.models.models import User, EmailLog +from app.services import email_service as es + +logger = logging.getLogger(__name__) + +# ── Constants ───────────────────────────────────────────────────────────────── + +# Max emails a user can receive per rolling period (excludes P0 transactional) +MAX_PER_DAY = 3 +MAX_PER_WEEK = 7 +MAX_PER_MONTH = 20 + +# Templates exempt from all caps and preference checks +P0_EXEMPT = { + "verification", "password_reset", "email_changed", + "password_changed", "new_device_login", "suspicious_login", + "account_locked", "payment_failed", +} + +# Per-template cooldown periods +COOLDOWNS: dict[str, timedelta] = { + "welcome": timedelta(days=9999), # once ever + "onboarding_nudge_3": timedelta(days=4), + "onboarding_nudge_7": timedelta(days=4), + "first_video": timedelta(days=9999), + "first_follower": timedelta(days=9999), + "first_like": timedelta(days=9999), + "first_comment": timedelta(days=9999), + "weekly_digest": timedelta(days=6), + "monthly_stats": timedelta(days=28), + "reengagement_3": timedelta(days=4), + "reengagement_7": timedelta(days=7), + "reengagement_14": timedelta(days=14), + "reengagement_30": timedelta(days=30), + "reengagement_60": timedelta(days=60), + "reengagement_90": timedelta(days=90), + "pro_upgrade": timedelta(days=9999), + "growth_tip": timedelta(days=7), + "milestone_followers": timedelta(days=1), + "milestone_views": timedelta(days=1), + "challenge_exit": timedelta(days=1), + "social_batch": timedelta(hours=24), + "security_new_device": timedelta(hours=1), +} + +# ── Helpers ─────────────────────────────────────────────────────────────────── + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def _last_sent(db: Session, user_id: int, template: str) -> datetime | None: + row = ( + db.query(EmailLog) + .filter_by(user_id=user_id, template=template) + .filter(EmailLog.bounced == False, EmailLog.unsubscribed == False) + .order_by(EmailLog.sent_at.desc()) + .first() + ) + return row.sent_at.replace(tzinfo=timezone.utc) if row else None + + +def _daily_count(db: Session, user_id: int) -> int: + since = _now() - timedelta(days=1) + return ( + db.query(EmailLog) + .filter(EmailLog.user_id == user_id, EmailLog.sent_at >= since) + .filter(~EmailLog.template.in_(P0_EXEMPT)) + .count() + ) + + +def _weekly_count(db: Session, user_id: int) -> int: + since = _now() - timedelta(days=7) + return ( + db.query(EmailLog) + .filter(EmailLog.user_id == user_id, EmailLog.sent_at >= since) + .filter(~EmailLog.template.in_(P0_EXEMPT)) + .count() + ) + + +def _log(db: Session, user_id: int, template: str, subject: str): + db.add(EmailLog(user_id=user_id, template=template, subject=subject)) + db.commit() + + +def _check_prefs(user: User, template: str) -> bool: + """Return True if user's email preferences allow this template.""" + if template in P0_EXEMPT: + return True + # Digest / tips / marketing + if template in ("weekly_digest", "monthly_stats", "growth_tip"): + return bool(user.email_weekly) + # Challenge-related + if template.startswith("challenge"): + return bool(user.email_challenges) + # Social (follower, like, comment) + if template in ("first_follower", "first_like", "first_comment", "social_batch"): + return True # user-level pref via notif_* columns + return True # default allow + + +def _can_send(db: Session, user: User, template: str) -> bool: + """Full gate check: prefs → caps → cooldown.""" + if not _check_prefs(user, template): + logger.debug("email blocked by prefs: user=%s template=%s", user.id, template) + return False + + if template not in P0_EXEMPT: + if _daily_count(db, user.id) >= MAX_PER_DAY: + logger.debug("email blocked by daily cap: user=%s", user.id) + return False + if _weekly_count(db, user.id) >= MAX_PER_WEEK: + logger.debug("email blocked by weekly cap: user=%s", user.id) + return False + + cooldown = COOLDOWNS.get(template) + if cooldown: + last = _last_sent(db, user.id, template) + if last and (_now() - last) < cooldown: + logger.debug("email blocked by cooldown: user=%s template=%s", user.id, template) + return False + + return True + + +# ── Main Service Class ──────────────────────────────────────────────────────── + +class EmailTrigger: + """ + Usage: + t = EmailTrigger(db) + t.welcome(user) + t.first_like(owner, liker, video) + """ + + def __init__(self, db: Session): + self.db = db + + def _fire(self, user: User, template: str, subject: str, fn, *args, **kwargs) -> bool: + if not _can_send(self.db, user, template): + return False + try: + ok = fn(*args, **kwargs) + if ok: + _log(self.db, user.id, template, subject) + return ok + except Exception as e: + logger.error("Email send error — template=%s user=%s: %s", template, user.id, e) + return False + + # ── Acquisition ─────────────────────────────────────────────────────────── + + def verification(self, user: User, code: str) -> bool: + return self._fire( + user, "verification", f"{code} is your Monteeq code", + es.send_verification_email, user.email, code, + ) + + def welcome(self, user: User) -> bool: + return self._fire( + user, "welcome", f"Welcome to Monteeq, {user.username}", + es.send_welcome_email, user.email, user.username, + ) + + def password_reset(self, user: User, token: str) -> bool: + return self._fire( + user, "password_reset", "Reset your Monteeq password", + es.send_password_reset_email, user.email, token, + ) + + # ── Activation ──────────────────────────────────────────────────────────── + + def onboarding_nudge(self, user: User, days: int) -> bool: + template = f"onboarding_nudge_{days}" + return self._fire( + user, template, "Your profile is ready — add your first video", + es.send_day3_nudge_email, user.email, user.username, + ) + + def first_video(self, user: User, video_title: str, video_url: str) -> bool: + return self._fire( + user, "first_video", f"Your video is live — {video_title}", + es.send_first_video_email, user.email, user.username, video_title, video_url, + ) + + def first_follower(self, user: User, follower_name: str) -> bool: + return self._fire( + user, "first_follower", f"{follower_name} followed you", + es.send_first_follower_email, user.email, user.username, follower_name, + ) + + def first_like(self, user: User, liker_name: str, video_title: str, video_url: str) -> bool: + return self._fire( + user, "first_like", "Your video got its first like", + es.send_first_like_email, user.email, user.username, video_title, liker_name, video_url, + ) + + def first_comment(self, user: User, video_title: str, commenter_name: str, comment_content: str, video_url: str) -> bool: + return self._fire( + user, "first_comment", f"New comment from {commenter_name}", + es.send_first_comment_email, user.email, user.username, video_title, commenter_name, comment_content, video_url, + ) + + def mention(self, user: User, mentioner_name: str, context_text: str, action_url: str) -> bool: + return self._fire( + user, "mention", f"{mentioner_name} mentioned you", + es.send_mention_email, user.email, user.username, mentioner_name, context_text, action_url, + ) + + + # ── Engagement ──────────────────────────────────────────────────────────── + + def weekly_digest(self, user: User, videos: list) -> bool: + return self._fire( + user, "weekly_digest", "This week on Monteeq", + es.send_weekly_digest_email, [user.email], videos, + ) + + def monthly_stats(self, user: User, month: str, stats: dict) -> bool: + return self._fire( + user, "monthly_stats", f"Your {month} stats on Monteeq", + es.send_monthly_stats_email, user.email, user.username, month, stats, + ) + + # ── Retention ──────────────────────────────────────────────────────────── + + def reengagement(self, user: User, inactive_days: int) -> bool: + template = f"reengagement_{inactive_days}" + return self._fire( + user, template, "Good time to post something new", + es.send_reengagement_email, user.email, user.username, inactive_days, + ) + + # ── Transactional ───────────────────────────────────────────────────────── + + def pro_upgrade(self, user: User) -> bool: + return self._fire( + user, "pro_upgrade", "You're now on Monteeq Pro", + es.send_pro_upgrade_email, user.email, user.username, + ) + + def challenge_exit(self, user: User, challenge_title: str) -> bool: + return self._fire( + user, "challenge_exit", f"Update on Challenge: {challenge_title}", + es.send_challenge_exit_email, user.email, user.username, challenge_title, + ) + + # ── Security & Subscription (Sprint 2 additions) ────────────────────────── + + def security(self, user: User, template_type: str, **kwargs) -> bool: + template = f"security_{template_type}" + return self._fire( + user, template, "Security notification", + es.send_security_email, user.email, template_type, user.username, **kwargs, + ) + + def subscription(self, user: User, template_type: str, **kwargs) -> bool: + template = f"subscription_{template_type}" + return self._fire( + user, template, "Subscription notification", + es.send_subscription_email, user.email, template_type, user.username, **kwargs, + ) + + # ── Growth, Celebration & Batching (Sprint 3 additions) ─────────────────── + + def growth_drip(self, user: User, week: int) -> bool: + template = f"growth_drip_{week}" + return self._fire( + user, template, "Creator growth tips", + es.send_growth_drip_email, user.email, user.username, week, + ) + + def celebration(self, user: User, template_type: str, **kwargs) -> bool: + template = f"celebration_{template_type}" + return self._fire( + user, template, "Congratulations!", + es.send_celebration_email, user.email, user.username, template_type, **kwargs, + ) + + def social_batch(self, user: User, summary_text: str) -> bool: + return self._fire( + user, "social_batch", "New activity on your profile", + es.send_social_batch_email, user.email, user.username, summary_text, + ) + diff --git a/app/services/recommendation_service.py b/app/services/recommendation_service.py new file mode 100644 index 0000000000000000000000000000000000000000..19c151abea8ec82366378175d744dc14b0e5acb8 --- /dev/null +++ b/app/services/recommendation_service.py @@ -0,0 +1,505 @@ +""" +recommendation_service.py +───────────────────────── +Monteeq – Universal Recommendation Engine + +Works for both video_type="flash" and video_type="home". + +Feed composition (per type): + 70% personalised – ranked by tag-affinity × discovery score + 20% trending – highest avg completion rate last 7 days globally + 10% exploration – new / low-view / unseen videos + +Scoring formula per interaction: + score = (completion_rate × 0.4) + (liked × 0.3) + + (replayed × 0.2) – (skipped_fast × 0.5) + +Tag affinity update (background): + affinity[tag] = affinity[tag] × 0.85 + score × 0.15 (EMA) +""" + +import json +import logging +import time +from datetime import datetime, timedelta +from typing import Dict, List, Optional, Tuple + +from sqlalchemy import desc, func +from sqlalchemy.orm import Session, joinedload + +from app.db.session import SessionLocal +from app.models.models import ( + Follow, + UserRecommendationProfile, + Video, + VideoInteraction, + Like +) + +log = logging.getLogger("monteeq.recommend") + +# ─── In-memory caches ──────────────────────────────────────────────────────── +# Key: (user_id, video_type) +_feed_cache: Dict[Tuple[int, str], Dict] = {} +CACHE_TTL_SECONDS = 45 + +# Skip-streak tracker — keyed by user_id (type-agnostic: rapid skipping on +# any feed indicates the same UX state) +_skip_streaks: Dict[int, int] = {} + +# ─── Scoring weights ───────────────────────────────────────────────────────── +WEIGHTS = { + "completion": 0.4, + "liked": 0.3, + "replayed": 0.2, + "skipped_fast": -0.5, +} + +FEED_SPLIT = {"personal": 0.70, "trending": 0.20, "explore": 0.10} + +# Exploration view-count thresholds (home videos naturally get more views) +EXPLORE_VIEW_THRESHOLD = { + "flash": 1_000, + "home": 5_000, +} + + +# ─── Scoring ────────────────────────────────────────────────────────────────── + +def compute_interaction_score( + watch_time: float, + duration: float, + liked: bool, + skipped: bool, # noqa: ARG001 – in payload for completeness, not used in formula + replayed: bool, +) -> Tuple[float, float, bool]: + """ + Returns (completion_rate, interaction_score, skipped_fast). + """ + safe_duration = max(duration, 0.001) + completion_rate = min(watch_time / safe_duration, 1.0) + skipped_fast = watch_time < 2.0 + + score = ( + completion_rate * WEIGHTS["completion"] + + int(liked) * WEIGHTS["liked"] + + int(replayed) * WEIGHTS["replayed"] + + int(skipped_fast) * WEIGHTS["skipped_fast"] + ) + return completion_rate, score, skipped_fast + + +# ─── Skip-streak helpers ────────────────────────────────────────────────────── + +def record_skip_event(user_id: int, watch_time: float) -> None: + if watch_time < 2.0: + _skip_streaks[user_id] = _skip_streaks.get(user_id, 0) + 1 + else: + _skip_streaks[user_id] = 0 + + +def get_skip_streak(user_id: int) -> int: + return _skip_streaks.get(user_id, 0) + + +# ─── Profile helpers ────────────────────────────────────────────────────────── + +def _get_or_create_profile(db: Session, user_id: int) -> UserRecommendationProfile: + profile = ( + db.query(UserRecommendationProfile) + .filter(UserRecommendationProfile.user_id == user_id) + .first() + ) + if not profile: + profile = UserRecommendationProfile(user_id=user_id) + db.add(profile) + db.commit() + db.refresh(profile) + return profile + + +def _read_affinity(profile: UserRecommendationProfile) -> Dict[str, float]: + try: + return json.loads(profile.tag_affinity or "{}") + except (ValueError, TypeError): + return {} + + +def _read_seen_ids(profile: UserRecommendationProfile) -> List[int]: + try: + return json.loads(profile.seen_video_ids or "[]") + except (ValueError, TypeError): + return {} + + +def _read_history(profile: UserRecommendationProfile) -> Dict[str, dict]: + try: + return json.loads(profile.watch_history or "{}") + except (ValueError, TypeError): + return {} + + +def update_user_profile_background( + user_id: int, + video_id: int, + score: float, + watch_time: float = 0.0, + completion_rate: float = 0.0 +) -> None: + """ + EMA update of the user's tag-affinity profile AND intelligent watch history tracking. + """ + db = SessionLocal() + try: + video = db.query(Video).filter(Video.id == video_id).first() + if not video: + return + + profile = _get_or_create_profile(db, user_id) + + # 1. Update Tag Affinity + if video.tags: + tags = [t.strip().lower() for t in video.tags.split(",") if t.strip()] + affinity = _read_affinity(profile) + alpha = 0.15 + for tag in tags: + current = affinity.get(tag, 0.0) + affinity[tag] = round(current * (1 - alpha) + score * alpha, 6) + profile.tag_affinity = json.dumps(affinity) + + # 2. Update Watch History (Intelligent) + # Structure: {"v_id": {"c": count, "t": last_timestamp, "wt": total_wt, "mc": max_completion}} + history = _read_history(profile) + vid_str = str(video_id) + + record = history.get(vid_str, {"c": 0, "t": 0, "wt": 0.0, "mc": 0.0}) + record["c"] += 1 + record["t"] = int(time.time()) + record["wt"] += watch_time + record["mc"] = max(record["mc"], completion_rate) + + history[vid_str] = record + + # Pruning: Keep only last 1000 interactions for performance + if len(history) > 1000: + # Drop the oldest timestamped entry + oldest_vid = min(history.keys(), key=lambda k: history[k]["t"]) + history.pop(oldest_vid) + + profile.watch_history = json.dumps(history) + + # 3. Legacy Compatibility (Append to seen_video_ids) + seen = _read_seen_ids(profile) + if video_id not in seen: + seen.append(video_id) + if len(seen) > 500: + seen = seen[-500:] + profile.seen_video_ids = json.dumps(seen) + + db.commit() + log.info("[recommend] Profile updated user=%d video=%d score=%.3f", user_id, video_id, score) + except Exception as exc: + db.rollback() + log.error("[recommend] Profile update failed: %s", exc) + finally: + db.close() + + +# ─── Query helpers ──────────────────────────────────────────────────────────── + +def _base_query(db: Session, video_type: str): + """Return a base query filtered to the given video_type, excluding failed or empty/corrupted videos.""" + return db.query(Video).options(joinedload(Video.owner)).filter( + Video.video_type == video_type, + Video.status == "approved", + Video.video_url != "", + Video.video_url.isnot(None), + ) + + +def _apply_exclude(query, exclude_ids: List[int]): + """Apply NOT IN filter only when the list is non-empty (guards bad SQL).""" + if exclude_ids: + return query.filter(Video.id.notin_(exclude_ids)) + return query + + +# ─── Feed segment builders ──────────────────────────────────────────────────── + +def _personalised_videos( + db: Session, + video_type: str, + affinity: Dict[str, float], + history: Dict[str, dict], + limit: int, + prefer_short: bool, +) -> List[Video]: + """ + Pull up to 200 candidates and score them with personalized affinity + MULTIPLIED by dynamic history weights (cooldown, repeat penalty, skip-boost). + """ + # We fetch more candidates than limit to allow room for scoring diversity + query = _base_query(db, video_type) + if prefer_short and video_type == "flash": + query = query.filter(Video.duration <= 20) + + candidates: List[Video] = query.order_by(desc(Video.discovery_score)).limit(300).all() + if not candidates: + return [] + + now = int(time.time()) + + def _calculate_multiplier(v: Video) -> float: + vid_str = str(v.id) + if vid_str not in history: + return 1.0 + + h = history[vid_str] + count = h.get("c", 0) + last_at = h.get("t", 0) + max_c = h.get("mc", 0.0) + total_wt = h.get("wt", 0.0) + + mult = 1.0 + + # 1. Cooldown (Strict) + if (now - last_at) < 7200: # 2 hours + mult *= 0.05 + + # 2. Diminishing Returns (Penalty per view) + mult *= (1.0 / (count + 1)) + + # 3. Skip-Retry (Boost for videos skipped instantly but seen once long ago) + if count == 1 and total_wt < 2.0 and (now - last_at) > 14400: # 4 hours + mult *= 2.0 + + # 4. Replay Allowance (Boost for high-engagement loops) + if max_c > 1.2: + mult *= 1.5 + + return mult + + scored_candidates = [] + for v in candidates: + tags = [t.strip().lower() for t in (v.tags or "").split(",") if t.strip()] + tag_score = sum(affinity.get(t, 0.0) for t in tags) + + base_score = (v.discovery_score or 0.0) * 0.5 + tag_score * 0.5 + multiplier = _calculate_multiplier(v) + + scored_candidates.append((v, base_score * multiplier)) + + scored_candidates.sort(key=lambda x: x[1], reverse=True) + return [x[0] for x in scored_candidates[:limit]] + + +def _trending_videos( + db: Session, + video_type: str, + history: Dict[str, dict], + limit: int, +) -> List[Video]: + """ + Trending videos, but filtered for history cooldowns. + """ + if limit <= 0: + return [] + + week_ago = datetime.utcnow() - timedelta(days=7) + now = int(time.time()) + + trending_sub = ( + db.query( + VideoInteraction.video_id.label("video_id"), + func.avg(VideoInteraction.completion_rate).label("avg_completion"), + ) + .filter(VideoInteraction.timestamp >= week_ago) + .group_by(VideoInteraction.video_id) + .having(func.count(VideoInteraction.id) >= 3) + .subquery() + ) + + base_query = ( + db.query(Video) + .options(joinedload(Video.owner)) + .join(trending_sub, Video.id == trending_sub.c.video_id) + .filter(Video.video_type == video_type, Video.status == "approved") + .order_by(desc(trending_sub.c.avg_completion)) + ) + + # We fetch more and manually filter cooldowns to ensure we return `limit` + candidates = base_query.limit(limit + 50).all() + + filtered = [] + for v in candidates: + h = history.get(str(v.id), {}) + # Penalty for very recent views in trending (variety) + if h and (now - h.get("t", 0)) < 3600: # 1 hour + continue + filtered.append(v) + if len(filtered) >= limit: + break + + return filtered or candidates[:limit] + + +def _exploration_videos( + db: Session, + video_type: str, + history: Dict[str, dict], + already_returned_ids: List[int], + limit: int, + prefer_short: bool, +) -> List[Video]: + """ + Exploration = low-view videos that haven't been seen much. + """ + if limit <= 0: + return [] + + view_threshold = EXPLORE_VIEW_THRESHOLD.get(video_type, 1_000) + seen_ids = [int(k) for k in history.keys()] + exclude = list(set(seen_ids + already_returned_ids)) + + query = ( + _apply_exclude(_base_query(db, video_type), exclude) + .filter(Video.views < view_threshold) + .order_by(func.random()) + ) + if prefer_short and video_type == "flash": + query = query.filter(Video.duration <= 20) + return query.limit(limit).all() + + +def _following_videos( + db: Session, + user_id: int, + video_type: str, + seen_ids: List[int], + limit: int, +) -> List[Video]: + """ + Following = videos from users that the current user follows. + """ + if limit <= 0: + return [] + + # Get IDs of followed users + followed_user_ids = [ + f.following_id for f in db.query(Follow.following_id).filter(Follow.follower_id == user_id).all() + ] + if not followed_user_ids: + return [] + + query = ( + _apply_exclude(_base_query(db, video_type), seen_ids) + .filter(Video.owner_id.in_(followed_user_ids)) + .order_by(desc(Video.created_at)) + ) + return query.limit(limit).all() + + +# ─── Cache helpers ──────────────────────────────────────────────────────────── + +def invalidate_cache(user_id: int, video_type: Optional[str] = None) -> None: + """ + Invalidate cached feed(s) for a user. + Pass video_type to clear only that feed; omit to clear all. + """ + if video_type: + _feed_cache.pop((user_id, video_type), None) + else: + for key in list(_feed_cache.keys()): + if key[0] == user_id: + _feed_cache.pop(key, None) + + +# ─── Public API ─────────────────────────────────────────────────────────────── + +def build_feed( + db: Session, + user_id: int, + video_type: str = "flash", + feed_type: str = "foryou", + limit: int = 20, + mood: Optional[str] = None, +) -> List[Video]: + """ + Assemble and return a ranked feed for `user_id` and `video_type`. + + video_type: "flash" | "home" + feed_type: "foryou" | "trending" | "following" + Cached per (user_id, video_type, feed_type) for CACHE_TTL_SECONDS seconds. + """ + cache_key = (user_id, video_type, feed_type) + cached = _feed_cache.get(cache_key) + if cached and (datetime.utcnow() - cached["ts"]).total_seconds() < CACHE_TTL_SECONDS: + log.debug("[recommend] Cache hit user=%d type=%s", user_id, video_type) + return cached["feed"] + + profile = _get_or_create_profile(db, user_id) + affinity = _read_affinity(profile) + history = _read_history(profile) + prefer_short = get_skip_streak(user_id) >= 3 + + personal, trending, explore = [], [], [] + + if feed_type == "trending": + trending = _trending_videos(db, video_type, history, limit) + feed = trending + elif feed_type == "following": + # For Following, we still use strict 'seen' list for now as variety is secondary to content + seen_ids = [int(k) for k in history.keys()] + personal = _following_videos(db, user_id, video_type, seen_ids, limit) + if not personal: + trending = _trending_videos(db, video_type, history, limit) + feed = trending + else: + feed = personal + else: # foryou + n_personal = max(1, round(limit * FEED_SPLIT["personal"])) + n_trending = max(1, round(limit * FEED_SPLIT["trending"])) + n_explore = max(1, limit - n_personal - n_trending) + + personal = _personalised_videos(db, video_type, affinity, history, n_personal, prefer_short) + personal_ids = [v.id for v in personal] + + trending = _trending_videos(db, video_type, history, n_trending) + trending_ids = [v.id for v in trending] + + explore = _exploration_videos( + db, video_type, history, personal_ids + trending_ids, n_explore, prefer_short + ) + feed = personal + trending + explore + + # Optional tag/mood filter + if mood: + mood_lc = mood.lower() + feed = [v for v in feed if mood_lc in (v.tags or "").lower()] + + # Deduplicate preserving order + seen_set: set = set() + deduped: List[Video] = [] + for v in feed: + if v.id not in seen_set: + deduped.append(v) + seen_set.add(v.id) + + # Single batch query to annotate liked_by_user + if deduped: + video_ids = [v.id for v in deduped] + liked_ids = { + r[0] + for r in db.query(Like.video_id) + .filter(Like.user_id == user_id, Like.video_id.in_(video_ids)) + .all() + } + for v in deduped: + v.liked_by_user = v.id in liked_ids + + _feed_cache[cache_key] = {"ts": datetime.utcnow(), "feed": deduped} + log.info( + "[recommend] Feed built user=%d type=%s personal=%d trending=%d explore=%d", + user_id, video_type, len(personal), len(trending), len(explore), + ) + return deduped diff --git a/app/tasks/__init__.py b/app/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/tasks/email_tasks.py b/app/tasks/email_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..111dd06ae628313453d184e71afdc5921913931f --- /dev/null +++ b/app/tasks/email_tasks.py @@ -0,0 +1,392 @@ +""" +Lifecycle email Celery tasks for Monteeq. +Registered in worker.py beat_schedule. +""" +import logging +from datetime import datetime, timedelta, timezone +from celery import shared_task + +from app.db.session import SessionLocal +from app.models.models import User, Challenge, Video +from app.services.email_service import ( + send_challenge_announcement_batch, + send_weekly_digest_email, + send_monthly_stats_email, +) +from app.services.email_trigger import EmailTrigger + +logger = logging.getLogger(__name__) + + +def _now(): + return datetime.now(timezone.utc) + + +def is_local_morning(user: User) -> bool: + """ + Check if the current time is local morning (09:00 to 11:00) for the user. + Estimates offset using user.country, falls back to UTC. + """ + offsets = { + "NG": 1, "NGR": 1, "NIGERIA": 1, + "GB": 1, "UK": 1, "UNITED KINGDOM": 1, + "US": -5, "USA": -5, "UNITED STATES": -5, + "CA": -5, "CANADA": -5, + "ZA": 2, "SOUTH AFRICA": 2, + "IN": 5.5, "INDIA": 5.5, + } + country = (user.country or "").upper().strip() + offset = offsets.get(country, 0) + # Convert timezone offset float/int to hours + local_hour = (datetime.now(timezone.utc) + timedelta(hours=offset)).hour + return 9 <= local_hour <= 11 + + + +# ── Challenge announcement (existing, kept for compat) ────────────────────── + +@shared_task(name="tasks.email.queue_new_challenge_announcement") +def queue_new_challenge_announcement(challenge_id: int): + """Fetch opted-in users and BCC them a challenge announcement.""" + db = SessionLocal() + try: + challenge = db.query(Challenge).filter(Challenge.id == challenge_id).first() + if not challenge: + logger.error("Challenge %s not found.", challenge_id) + return + + subscribers = db.query(User).filter( + User.email_challenges == True, + User.email.isnot(None), + ).all() + + if not subscribers: + logger.info("No opted-in users. Skipping challenge announcement.") + return + + emails = [u.email for u in subscribers] + end_date_str = challenge.end_date.strftime("%B %d, %Y") if challenge.end_date else "TBD" + + for i in range(0, len(emails), 50): + batch = emails[i:i + 50] + send_challenge_announcement_batch( + bcc_emails=batch, + title=challenge.title, + prize=challenge.prize, + end_date=end_date_str, + ) + logger.info("Challenge '%s' announced to %d users.", challenge.title, len(emails)) + except Exception as e: + logger.error("queue_new_challenge_announcement failed: %s", e) + finally: + db.close() + + +# ── Inactivity ladder (runs daily at 09:00 UTC) ────────────────────────────── + +@shared_task(name="tasks.email.check_inactivity") +def check_inactivity(): + """ + Checks users at each inactivity threshold and queues re-engagement emails. + Only one tier fires per user per run (the most urgent matching threshold). + """ + db = SessionLocal() + try: + thresholds = [3, 7, 14, 30, 60, 90] + trigger = EmailTrigger(db) + + for days in thresholds: + window_end = _now() - timedelta(days=days) + window_start = window_end - timedelta(hours=23, minutes=59) + + users = ( + db.query(User) + .filter( + User.is_active == True, + User.email_marketing == True, + ) + .all() + ) + + sent = 0 + for user in users: + if not is_local_morning(user): + continue + last_active = getattr(user, "last_active", None) or user.created_at + if last_active and hasattr(last_active, "replace"): + last_active = last_active.replace(tzinfo=timezone.utc) + if last_active and window_start <= last_active <= window_end: + if trigger.reengagement(user, days): + sent += 1 + + if sent: + logger.info("Inactivity D%d: sent %d re-engagement emails.", days, sent) + except Exception as e: + logger.error("check_inactivity failed: %s", e) + finally: + db.close() + + +# ── Onboarding nudge check (runs hourly) ───────────────────────────────────── + +@shared_task(name="tasks.email.check_onboarding_nudges") +def check_onboarding_nudges(): + """ + Fire D+3 and D+7 nudges for users who signed up exactly N days ago + and still have no uploads. + """ + db = SessionLocal() + try: + trigger = EmailTrigger(db) + + for days in [3, 7]: + window_end = _now() - timedelta(days=days) + window_start = window_end - timedelta(hours=1) + + candidates = ( + db.query(User) + .filter( + User.is_active == True, + User.created_at >= window_start, + User.created_at < window_end, + User.home_uploads == 0, + User.flash_uploads == 0, + ) + .all() + ) + + sent = 0 + for user in candidates: + if trigger.onboarding_nudge(user, days): + sent += 1 + + if sent: + logger.info("Onboarding D%d: sent %d nudge emails.", days, sent) + except Exception as e: + logger.error("check_onboarding_nudges failed: %s", e) + finally: + db.close() + + +# ── Weekly digest (runs Monday 09:00 UTC) ──────────────────────────────────── + +@shared_task(name="tasks.email.send_weekly_digest_batch") +def send_weekly_digest_batch(): + """ + Pull top 5 approved videos from last 7 days and email all opted-in users. + Personalisation per user can be added in a later sprint. + """ + db = SessionLocal() + try: + week_ago = _now() - timedelta(days=7) + top_videos = ( + db.query(Video) + .filter( + Video.status == "approved", + Video.created_at >= week_ago, + ) + .order_by(Video.views.desc()) + .limit(5) + .all() + ) + + if not top_videos: + logger.info("No videos for weekly digest. Skipping.") + return + + video_dicts = [ + { + "title": v.title, + "creator": f"@{v.owner.username}" if v.owner else "", + "url": f"https://monteeq.com/watch/{v.public_id}", + } + for v in top_videos + ] + + trigger = EmailTrigger(db) + users = db.query(User).filter( + User.is_active == True, + User.email_weekly == True, + User.email.isnot(None), + ).all() + + sent = 0 + for user in users: + if not is_local_morning(user): + continue + if trigger.weekly_digest(user, video_dicts): + sent += 1 + + logger.info("Weekly digest sent to %d users.", sent) + except Exception as e: + logger.error("send_weekly_digest_batch failed: %s", e) + finally: + db.close() + + +# ── Monthly stats (runs 1st of month, 10:00 UTC) ───────────────────────────── + +@shared_task(name="tasks.email.send_monthly_stats_batch") +def send_monthly_stats_batch(): + """ + Compute last month's stats per creator and send individual recap emails. + """ + from calendar import month_name + from sqlalchemy import func as sqlfunc + + db = SessionLocal() + try: + now = _now() + last_month_start = (now.replace(day=1) - timedelta(days=1)).replace(day=1, tzinfo=timezone.utc) + last_month_end = now.replace(day=1, tzinfo=timezone.utc) + month_label = month_name[last_month_start.month] + + creators = db.query(User).filter( + User.is_active == True, + User.email_weekly == True, + User.home_uploads + User.flash_uploads > 0, + ).all() + + trigger = EmailTrigger(db) + sent = 0 + for user in creators: + # Aggregate stats for this user's videos in last month + from app.models.models import View, Like + views = db.query(sqlfunc.count(View.id)).filter( + View.user_id == user.id, + View.created_at >= last_month_start, + View.created_at < last_month_end, + ).scalar() or 0 + + likes = db.query(sqlfunc.count(Like.id)).join(Video).filter( + Video.owner_id == user.id, + Like.created_at >= last_month_start, + Like.created_at < last_month_end, + ).scalar() or 0 + + from app.models.models import Follow + new_followers = db.query(sqlfunc.count(Follow.id)).filter( + Follow.following_id == user.id, + Follow.created_at >= last_month_start, + Follow.created_at < last_month_end, + ).scalar() or 0 + + new_uploads = db.query(sqlfunc.count(Video.id)).filter( + Video.owner_id == user.id, + Video.created_at >= last_month_start, + Video.created_at < last_month_end, + ).scalar() or 0 + + stats = { + "views": views, + "likes": likes, + "followers": new_followers, + "uploads": new_uploads, + } + + if trigger.monthly_stats(user, month_label, stats): + sent += 1 + + logger.info("Monthly stats sent to %d creators.", sent) + except Exception as e: + logger.error("send_monthly_stats_batch failed: %s", e) + finally: + db.close() + + +# ── Creator growth drip (runs Tuesday 10:00 UTC) ────────────────────────────── + +@shared_task(name="tasks.email.send_growth_drip") +def send_growth_drip(): + """ + Send weekly creator tips to users who uploaded at least one video, + calculated based on the week number of their account age (Week 1 to 5). + """ + db = SessionLocal() + try: + trigger = EmailTrigger(db) + # Find active users with at least 1 upload + users = db.query(User).filter( + User.is_active == True, + User.email_marketing == True, + User.home_uploads + User.flash_uploads > 0, + ).all() + + sent = 0 + for user in users: + if not is_local_morning(user): + continue + age_days = (_now() - user.created_at.replace(tzinfo=timezone.utc)).days + week = (age_days // 7) + 1 + if 1 <= week <= 5: + if trigger.growth_drip(user, week): + sent += 1 + logger.info("Growth drip sent to %d users.", sent) + except Exception as e: + logger.error("send_growth_drip failed: %s", e) + finally: + db.close() + + +# ── Social notifications batching (runs every 4 hours or daily) ─────────────── + +@shared_task(name="tasks.email.flush_social_batch") +def flush_social_batch(): + """ + Gather likes, follows, and comments from the last 24 hours, + and send a summarized social activity batch email. + """ + from sqlalchemy import func as sqlfunc + from app.models.models import Like, Follow, Comment + + db = SessionLocal() + try: + trigger = EmailTrigger(db) + since = _now() - timedelta(hours=24) + + # Find users who have received actions + users = db.query(User).filter(User.is_active == True).all() + sent = 0 + + for user in users: + # Likes received on user's videos + likes_count = db.query(sqlfunc.count(Like.id)).join(Video).filter( + Video.owner_id == user.id, + Like.created_at >= since, + ).scalar() or 0 + + # Follows received + follows_count = db.query(sqlfunc.count(Follow.id)).filter( + Follow.following_id == user.id, + Follow.created_at >= since, + ).scalar() or 0 + + # Comments received + comments_count = db.query(sqlfunc.count(Comment.id)).join(Video).filter( + Video.owner_id == user.id, + Comment.created_at >= since, + ).scalar() or 0 + + if likes_count == 0 and follows_count == 0 and comments_count == 0: + continue + + # Construct simple recap summary + parts = [] + if follows_count > 0: + parts.append(f"- {follows_count} new follower{'s' if follows_count > 1 else ''}") + if likes_count > 0: + parts.append(f"- {likes_count} new like{'s' if likes_count > 1 else ''} on your edits") + if comments_count > 0: + parts.append(f"- {comments_count} new comment{'s' if comments_count > 1 else ''} on your videos") + + summary_text = "\n".join(parts) + + if trigger.social_batch(user, summary_text): + sent += 1 + + logger.info("Social notification recap batch flushed to %d users.", sent) + except Exception as e: + logger.error("flush_social_batch failed: %s", e) + finally: + db.close() + diff --git a/app/tasks/morning_notifications.py b/app/tasks/morning_notifications.py new file mode 100644 index 0000000000000000000000000000000000000000..78d7089414b570f5f363451783edc5aa03943089 --- /dev/null +++ b/app/tasks/morning_notifications.py @@ -0,0 +1,129 @@ +""" +Morning notification task — runs daily at 8 AM UTC via Celery Beat. + +For each active user who has opted into marketing/weekly emails, we pick +the top recommended home video from their personalised feed and send: + - An in-app notification (always stored in DB) + - A web push (if subscribed) + - An email (if email_marketing == True) +""" +import logging +from celery import shared_task +from app.db.session import SessionLocal +from app.models.models import User +from app.utils.push import notify_user_push +from app.services import recommendation_service as rs + +logger = logging.getLogger(__name__) + +# Greetings rotate so it feels fresh +_GREETINGS = [ + "Good morning! 🌅", + "Rise and edit! ✂️", + "Morning! Your feed is ready 🎬", + "Start your day with a great edit 🌄", + "Good morning — new content awaits! 🎥", +] + +import hashlib +from datetime import date + + +def _greeting_for_user(user_id: int) -> str: + """Deterministically pick a greeting based on user_id + today's date.""" + seed = hashlib.md5(f"{user_id}-{date.today().isoformat()}".encode()).hexdigest() + idx = int(seed, 16) % len(_GREETINGS) + return _GREETINGS[idx] + + +@shared_task(name="tasks.morning.send_morning_notifications") +def send_morning_notifications(): + """ + Celery Beat task: send a personalised good-morning notification to + every active user who has opted in (email_marketing OR notif_new_follower + acts as the general notification opt-in gate). + + We use email_marketing as the explicit opt-in for promotional/morning + messages so users who disabled it are not disturbed. + """ + db = SessionLocal() + sent = 0 + skipped = 0 + errors = 0 + + try: + # Fetch users who are active and haven't explicitly opted out of marketing + users = ( + db.query(User) + .filter( + User.is_active == True, + User.email_marketing == True, + User.email.isnot(None), + ) + .all() + ) + + logger.info(f"[morning_notif] Starting for {len(users)} opted-in users") + + for user in users: + try: + # Get 1 personalised home video recommendation + feed = rs.build_feed( + db, + user_id=user.id, + video_type="home", + feed_type="foryou", + limit=1, + ) + + if not feed: + # Fall back to a trending video + feed = rs._trending_videos(db, video_type="home", history={}, limit=1) + + if not feed: + skipped += 1 + continue + + video = feed[0] + greeting = _greeting_for_user(user.id) + title = greeting + body = f'Watch "{video.title}" — recommended just for you.' + link = f"/watch/{video.id}" + + notify_user_push( + db, + user_id=user.id, + title=title, + body=body, + link=link, + n_type="morning", + ) + + if user.email_marketing and user.email: + try: + from app.services.email_service import send_email + send_email( + to_email=user.email, + subject=f"{greeting} — Your Monteeq pick today", + title=greeting, + message=body, + action_text="Watch Now", + action_url=f"https://monteeq.com{link}", + ) + except Exception as e: + logger.error(f"[morning_notif] Email failed for user {user.id}: {e}") + + sent += 1 + + except Exception as e: + errors += 1 + logger.error(f"[morning_notif] Failed for user {user.id}: {e}") + + logger.info( + f"[morning_notif] Done — sent={sent}, skipped={skipped}, errors={errors}" + ) + + except Exception as e: + logger.error(f"[morning_notif] Fatal error: {e}") + finally: + db.close() diff --git a/app/tasks/video_tasks.py b/app/tasks/video_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..5415a3b3c8f27af66922ba7a5ad87a21421bfd8d --- /dev/null +++ b/app/tasks/video_tasks.py @@ -0,0 +1,262 @@ +import os +import time +import requests +from celery import shared_task +from sqlalchemy import func + +from app.db.session import SessionLocal +from app.models.models import Video, User +from app.core import config +from app.core.storage import storage +from app.utils.push import notify_user_push +from app.core.redis import redis_client +import logging +import json + +logger = logging.getLogger(__name__) + +@shared_task(bind=True, name="video_tasks.process_video", max_retries=3) +def process_video_task(self, source_key: str, video_type: str, title: str, video_id: int, thumbnail_provided: bool, task_id: str): + logger.info(f"Starting Celery task: video_id={video_id}, task_id={task_id}") + db = SessionLocal() + try: + # Phase 1: Communication with Rust Service + try: + logger.info(f"Phase 1: POST to Rust service at {config.RUST_SERVICE_URL}/process with source {source_key}") + try: + rust_response = requests.post( + f"{config.RUST_SERVICE_URL}/process", + json={ + "video_id": source_key, + "target_format": video_type, + "skip_thumbnail": thumbnail_provided, + "task_id": task_id + }, + timeout=30.0 # Increased timeout to 30s to allow for Render cold starts + ) + logger.info(f"Rust service responded with status {rust_response.status_code}") + rust_response.raise_for_status() + except requests.exceptions.RequestException as re: + logger.error(f"Failed to communicate with Rust service: {str(re)}") + if hasattr(re, 'response') and re.response is not None: + logger.error(f"Rust error response: {re.response.text}") + raise Exception(f"Rust service unreachable or returned error: {re}") + logger.info(f"Rust service accepted task. Starting polling for task_id={task_id}") + max_retries = 300 # 10 minutes with 2s sleep + retries = 0 + while retries < max_retries: + try: + # Priority 1: Check Redis (Shared with Rust) + status_data_raw = redis_client.get(f"task:status:{task_id}") + status_data = None + + if status_data_raw: + status_data = json.loads(status_data_raw) + else: + # Priority 2: Fallback to HTTP (If Redis is inconsistent or Rust is updating differently) + status_resp = requests.get(f"{config.RUST_SERVICE_URL}/status/{task_id}", timeout=2.0) + if status_resp.status_code == 200: + status_data = status_resp.json() + + if status_data: + current_status = status_data.get("status") + progress = status_data.get("progress", 0) + msg = status_data.get("message", "") + + logger.debug(f"Task {task_id} status: {current_status} ({progress}%)") + + # Provide progress update to DB + db_video = db.query(Video).filter(Video.id == video_id).first() + if db_video: + db_video.processing_message = f"{msg} ({progress}%)" + db.commit() + + if current_status and current_status.lower() in ["completed", "uploaded", "success"]: + logger.info(f"Transcoding completed for task_id={task_id}") + break + if current_status == "error": + logger.error(f"Rust processing error for task {task_id}: {msg}") + raise Exception(f"Rust processing error: {msg}") + else: + logger.warning(f"Task {task_id} status not found in Redis or Rust API.") + + except Exception as e: + if "Rust processing error" in str(e): raise e + logger.warning(f"Polling error (try {retries}): {e}") + + time.sleep(3) + retries += 1 + + if retries >= max_retries: + logger.error(f"Background processing timed out for task {task_id}") + raise Exception(f"Background processing timed out for task {task_id}") + + except Exception as e: + print(f"Error in background processing phase: {e}") + + # Only fail permanently if we've exhausted retries + if self.request.retries >= self.max_retries: + video = db.query(Video).filter(Video.id == video_id).first() + if video: + video.status = "failed" + video.failed_at = func.now() + owner = db.query(User).filter(User.id == video.owner_id).first() + if owner: + if video.video_type == "flash": + owner.flash_uploads = max(0, (owner.flash_uploads or 1) - 1) + else: + owner.home_uploads = max(0, (owner.home_uploads or 1) - 1) + db.commit() + + # Cleanup cloud storage on final failure + try: + logger.info(f"Cleaning up storage after final failure for task {task_id}") + storage.delete_prefix(f"uploads/{task_id}/") + storage.delete_prefix(f"videos/{task_id}/") + except Exception as cleanup_err: + logger.warning(f"Storage cleanup failed: {cleanup_err}") + + raise e + else: + logger.warning(f"Task {task_id} failed, retrying... ({self.request.retries}/{self.max_retries})") + raise self.retry(exc=e, countdown=60) + + # Phase 2: Post-processing (Updating DB URLs) + # Note: Rust service now handles the upload of HLS files to GCS. + logger.info(f"Phase 2: Updating DB with S3 URLs for video_id={video_id}") + + # Use storage abstraction to generate correct URLs (S3 or Local) + video_url = storage.get_url(f"videos/{task_id}/master.m3u8") + + if video_type == "flash": + url_480p = None + url_720p = None + url_1080p = None + url_2k = None + url_4k = None + else: + url_480p = storage.get_url(f"videos/{task_id}/480p.m3u8") + url_720p = storage.get_url(f"videos/{task_id}/720p.m3u8") + url_1080p = storage.get_url(f"videos/{task_id}/1080p.m3u8") + url_2k = storage.get_url(f"videos/{task_id}/2k.m3u8") + url_4k = storage.get_url(f"videos/{task_id}/4k.m3u8") + + thumbnail_url = storage.get_url(f"thumbnails/{task_id}.jpg") + + # Duration is not available from the Rust service response yet; + # keep as 0 — can be backfilled later via a separate metadata job. + duration = 0 + + video = db.query(Video).filter(Video.id == video_id).first() + if video: + video.video_url = video_url + video.url_480p = url_480p + video.url_720p = url_720p + video.url_1080p = url_1080p + video.url_2k = url_2k + video.url_4k = url_4k + video.duration = duration + video.failed_at = None + # Auto-approve: no admin review needed + video.status = "approved" + video.processing_message = "Live" + + # Only set thumbnail if a custom one wasn't provided during upload + if not thumbnail_provided and thumbnail_url: + video.thumbnail_url = thumbnail_url + + db.commit() + + # Notify user of success + try: + notify_user_push( + db, + user_id=video.owner_id, + title="Video Live! 🚀", + body=f"Your video '{title}' has been processed and is now live!", + link=f"/profile", + n_type="status_change" + ) + except: pass + + + + # Phase 3: Cleanup + try: + logger.info(f"Phase 3: Deleting raw source directory uploads/{task_id}/") + storage.delete_prefix(f"uploads/{task_id}/") + except Exception as e: + logger.warning(f"Failed to delete source directory uploads/{task_id}/: {e}") + + return {"status": "success", "video_id": video_id} + + except Exception as e: + # Notify user of failure and set status + try: + video = db.query(Video).filter(Video.id == video_id).first() + if video: + video.status = "failed" + video.failed_at = func.now() + owner = db.query(User).filter(User.id == video.owner_id).first() + if owner: + if video.video_type == "flash": + owner.flash_uploads = max(0, (owner.flash_uploads or 1) - 1) + else: + owner.home_uploads = max(0, (owner.home_uploads or 1) - 1) + db.commit() + + notify_user_push( + db, + user_id=video.owner_id, + title="Video Processing Failed", + body=f"Something went wrong while processing '{title}'. Please try uploading again.", + link="/upload", + n_type="status_change" + ) + + # Cleanup cloud storage on failure + logger.info(f"Cleaning up storage after phase 2 failure for task {task_id}") + storage.delete_prefix(f"uploads/{task_id}/") + storage.delete_prefix(f"videos/{task_id}/") + except: pass + + print(f"Error in post-processing: {e}") + raise e + finally: + db.close() + +@shared_task(name="video_tasks.update_discovery_score") +def update_discovery_score_task(video_id: int = None, post_id: int = None): + from datetime import datetime + from app.models.models import Post + db = SessionLocal() + try: + target = None + if video_id: + target = db.query(Video).filter(Video.id == video_id).first() + elif post_id: + target = db.query(Post).filter(Post.id == post_id).first() + + if not target: + return + + likes_count = target.likes_count or 0 + comments_count = target.comments_count or 0 + shares_count = target.shares if video_id else 0 + views_count = target.views if video_id else target.views_count + + score = (likes_count * 10) + (comments_count * 20) + (shares_count * 30) + ((views_count or 0) * 1) + + if target.last_owner_interaction_at: + score += 50 + + age_seconds = (datetime.now() - target.created_at).total_seconds() + age_hours = max(age_seconds / 3600, 0) + + gravity = 1.8 + final_score = score / pow((age_hours + 2), gravity) + + target.discovery_score = final_score + db.commit() + finally: + db.close() diff --git a/app/utils/push.py b/app/utils/push.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cb032b04723957ea2f120ccda971acfcc9f0e3 --- /dev/null +++ b/app/utils/push.py @@ -0,0 +1,95 @@ +import json +import os +from pywebpush import webpush, WebPushException +from app.models.models import PushSubscription +from sqlalchemy.orm import Session +import logging +from app.crud.notification import create_notification +from app.schemas.notification import NotificationCreate + +logger = logging.getLogger(__name__) + +VAPID_PRIVATE_KEY = os.getenv("VAPID_PRIVATE_KEY") +VAPID_PUBLIC_KEY = os.getenv("VAPID_PUBLIC_KEY") +VAPID_EMAIL = os.getenv("VAPID_EMAIL", "mailto:admin@monteeq.com") + +def send_push_notification(subscription: PushSubscription, message_data: dict): + try: + webpush( + subscription_info={ + "endpoint": subscription.endpoint, + "keys": { + "p256dh": subscription.p256dh, + "auth": subscription.auth + } + }, + data=json.dumps(message_data), + vapid_private_key=VAPID_PRIVATE_KEY, + vapid_claims={ + "sub": VAPID_EMAIL if VAPID_EMAIL.startswith("mailto:") else f"mailto:{VAPID_EMAIL}", + } + ) + return True + except WebPushException as ex: + logger.error("WebPush error: %s", ex) + # If subscription is no longer valid, we should probably delete it + # but we don't have db here. Caller should handle. + return False + except Exception as ex: + logger.error("Failed to send push: %s", ex) + return False + +from app.services.email_service import send_email +from app.models.models import User + +def notify_user_push(db: Session, user_id: int, title: str, body: str, link: str = None, n_type: str = "info"): + """ + Unified dispatcher for in-app notifications, web push, and email. + """ + # 1. Fetch user to check preferences and email + user = db.query(User).filter(User.id == user_id).first() + if not user: + return + + # 2. Always save to database for In-App history + notif_in = NotificationCreate( + user_id=user_id, + message=body, + link=link, + type=n_type + ) + create_notification(db, notif_in) + + # 3. Trigger Email if applicable + # We map notification types to user email preferences + should_email = False + if n_type == "follower" and user.notif_new_follower: should_email = True + elif n_type == "achievement" and user.notif_challenge_win: should_email = True + elif n_type == "comment" and user.notif_comments: should_email = True + elif n_type == "status_change": should_email = True # Vital status changes always email + elif n_type == "morning" and user.email_marketing: should_email = True + + if should_email and user.email: + send_email( + to_email=user.email, + subject=f"Monteeq: {title}", + title=title, + message=body, + action_text="View on Monteeq" if link else None, + action_url=link + ) + + # 4. Trigger Web Push if subscribed + from app.crud.notification import get_user_push_subscriptions + subscriptions = get_user_push_subscriptions(db, user_id) + if subscriptions: + payload = { + "title": title, + "body": body, + "icon": "/logo192.png", + "data": { + "url": link + } + } + for sub in subscriptions: + send_push_notification(sub, payload) diff --git a/app/utils/unsubscribe_token.py b/app/utils/unsubscribe_token.py new file mode 100644 index 0000000000000000000000000000000000000000..7d6ea894a82e3acd64bfc5434b970e9e6e9d73b5 --- /dev/null +++ b/app/utils/unsubscribe_token.py @@ -0,0 +1,66 @@ +""" +Unsubscribe token utility for Monteeq email links. + +Each email footer contains a one-click unsubscribe link: + https://monteeq.com/api/v1/email/unsubscribe?token= + +The token is an HMAC-signed payload: base64(user_id:template_group:ts) +No database lookup needed to verify — stateless. +""" + +import base64 +import hashlib +import hmac +import time +from typing import Optional + +from app.core.config import SECRET_KEY + +_SEP = ":" + + +def _sign(payload: str) -> str: + return hmac.new( + SECRET_KEY.encode(), + payload.encode(), + hashlib.sha256, + ).hexdigest()[:16] + + +def generate_unsubscribe_token(user_id: int, group: str = "marketing") -> str: + """ + Generate a signed unsubscribe token. + + group options: + 'marketing' — weekly digest, tips, platform news + 'social' — likes, followers, comments + 'challenges' — challenge emails + 'all' — everything except P0 transactional + """ + ts = int(time.time()) + payload = f"{user_id}{_SEP}{group}{_SEP}{ts}" + sig = _sign(payload) + raw = f"{payload}{_SEP}{sig}" + return base64.urlsafe_b64encode(raw.encode()).decode() + + +def verify_unsubscribe_token(token: str, max_age_days: int = 30) -> Optional[tuple[int, str]]: + """ + Verify token and return (user_id, group) or None if invalid/expired. + """ + try: + raw = base64.urlsafe_b64decode(token.encode()).decode() + parts = raw.split(_SEP) + if len(parts) != 4: + return None + user_id_str, group, ts_str, provided_sig = parts + payload = f"{user_id_str}{_SEP}{group}{_SEP}{ts_str}" + expected = _sign(payload) + if not hmac.compare_digest(expected, provided_sig): + return None + age = time.time() - int(ts_str) + if age > max_age_days * 86400: + return None + return int(user_id_str), group + except Exception: + return None diff --git a/app/worker.py b/app/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..265d659310310f3cb5a11c57390a63e0d3ebdf83 --- /dev/null +++ b/app/worker.py @@ -0,0 +1,77 @@ +import socket +import sys + +# Refuse execution on the specific Google Cloud instance +if socket.gethostname() == "instance-20260427-114320": + sys.exit("Error: Celery is not allowed to run on instance-20260427-114320.") + +from celery import Celery +from celery.schedules import crontab +from app.core.config import REDIS_URL + +celery_app = Celery( + "monteeq_worker", + broker=REDIS_URL, + # result_backend removed to save connections + include=[ + "app.tasks.video_tasks", + "app.tasks.email_tasks", + "app.tasks.morning_notifications", + ] +) + +celery_app.conf.update( + task_serializer="json", + accept_content=["json"], + result_serializer="json", + timezone="UTC", + enable_utc=True, + task_track_started=True, + task_time_limit=3600, + broker_pool_limit=20, + redis_max_connections=20, + worker_concurrency=4, + broker_transport_options={ + 'visibility_timeout': 3600, + 'max_connections': 20 + }, + beat_schedule={ + # Morning push notifications — daily 08:00 UTC + "morning-notifications-daily": { + "task": "tasks.morning.send_morning_notifications", + "schedule": crontab(hour=8, minute=0), + }, + # Onboarding nudge check — every hour (catches D+3 and D+7 windows) + "check-onboarding-nudges": { + "task": "tasks.email.check_onboarding_nudges", + "schedule": crontab(minute=0), + }, + # Inactivity ladder — hourly check (sends during local morning) + "check-inactivity": { + "task": "tasks.email.check_inactivity", + "schedule": crontab(minute=0), + }, + # Weekly digest — hourly on Monday (sends during local morning) + "weekly-digest": { + "task": "tasks.email.send_weekly_digest_batch", + "schedule": crontab(minute=0, day_of_week=1), + }, + # Monthly stats — 1st of every month, 10:00 UTC + "monthly-stats": { + "task": "tasks.email.send_monthly_stats_batch", + "schedule": crontab(hour=10, minute=0, day_of_month=1), + }, + # Creator growth drip — hourly on Tuesday (sends during local morning) + "creator-growth-tips": { + "task": "tasks.email.send_growth_drip", + "schedule": crontab(minute=0, day_of_week=2), + }, + # Social activity batch digest — daily 18:00 UTC + "flush-social-activity-batch": { + "task": "tasks.email.flush_social_batch", + "schedule": crontab(hour=18, minute=0), + }, + }, +) + + diff --git a/inject_err_message.py b/inject_err_message.py new file mode 100644 index 0000000000000000000000000000000000000000..4feafdb2ffd1c404bd1d301c3d49dc143d443e70 --- /dev/null +++ b/inject_err_message.py @@ -0,0 +1,36 @@ +import os +import re + +frontend_dir = '../frontend/src' + +for root, _, files in os.walk(frontend_dir): + for file in files: + if file.endswith(('.jsx', '.js')): + path = os.path.join(root, file) + with open(path, 'r') as f: + content = f.read() + + # Find showNotification('error', 'String') and replace with err?.message || 'String' + # We ONLY want to replace if there isn't already err.message or err.response etc. + # Regex: showNotification\(\s*(['"]error['"])\s*,\s*(['"].*?['"])\s*\) + # We'll replace it with: showNotification(\1, err?.message || \2) + + def replacer(match): + error_arg = match.group(1) + message_arg = match.group(2) + # If message already contains err, skip + if 'err' in message_arg: + return match.group(0) + + return f"showNotification({error_arg}, err?.message || {message_arg})" + + new_content = re.sub( + r"showNotification\(\s*(['\"]error['\"])\s*,\s*(['\"].*?['\"])\s*\)", + replacer, + content + ) + + if new_content != content: + with open(path, 'w') as f: + f.write(new_content) + print(f"Injected err?.message in {path}") diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..addbc69f926a98272a96e8ee3a178b24d2ac6eee --- /dev/null +++ b/main.py @@ -0,0 +1,174 @@ +from fastapi import FastAPI, Depends, Request, WebSocket, WebSocketDisconnect, Query +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse +from app.api.v1.api import api_router +from app.api.v1.endpoints import seo +from app.core import dependencies +from app.core.error_handlers import register_exception_handlers +from fastapi.middleware.gzip import GZipMiddleware +from fastapi_cache import FastAPICache +from fastapi_cache.backends.redis import RedisBackend +from redis import asyncio as aioredis + + +# Database initialized via Supabase schema +import app.worker + +from fastapi.staticfiles import StaticFiles +from starlette.middleware.base import BaseHTTPMiddleware +import uuid +import logging +import os + +logger = logging.getLogger("monteeq") + +app = FastAPI( + title="Monteeq Video Platform", + version="1.0.0", + docs_url="/docs", + redoc_url="/redoc", +) + +app.add_middleware(GZipMiddleware, minimum_size=1000) + + +# ── Request-ID Middleware ────────────────────────────────────────────────────── +class RequestIDMiddleware(BaseHTTPMiddleware): + """Attach a unique X-Request-ID to every request/response for tracing.""" + async def dispatch(self, request: Request, call_next): + request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4()) + request.state.request_id = request_id + response = await call_next(request) + response.headers["X-Request-ID"] = request_id + return response + +app.add_middleware(RequestIDMiddleware) + +# ── Anti-Bot Middleware ─────────────────────────────────────────────────────── +class AntiBotMiddleware(BaseHTTPMiddleware): + """Identify and block malicious bots globally with CORS support.""" + async def dispatch(self, request: Request, call_next): + from app.core import security + + # 1. Skip check for OPTIONS (CORS preflight), static files, health, and SEO/Sitemaps + if (request.method == "OPTIONS" or + request.url.path.startswith("/static") or + request.url.path == "/health" or + "/seo/" in request.url.path or + "sitemap" in request.url.path): + return await call_next(request) + + # 2. Heuristic check + if security.is_bot(request): + ua = request.headers.get("User-Agent", "Unknown") + logger.warning(f"Bot detected and blocked: {ua} from {request.client.host if request.client else 'unknown'}") + + response = JSONResponse( + status_code=403, + content={"detail": "Access denied. Automated traffic detected.", "ua": ua} + ) + + # Manually add CORS headers to ensure the browser doesn't throw a generic 'Failed to fetch' + origin = request.headers.get("Origin") + if origin: + # Basic validation: only allow our known domains + if any(domain in origin for domain in ["monteeq.com", "localhost"]): + response.headers["Access-Control-Allow-Origin"] = origin + response.headers["Access-Control-Allow-Credentials"] = "true" + + return response + + return await call_next(request) + +app.add_middleware(AntiBotMiddleware) + +# CORS middleware - MUST be added before other middleware +app.add_middleware( + CORSMiddleware, + allow_origins=[ + "https://www.monteeq.com", + "https://monteeq.com", + "https://admin.monteeq.com", + "https://www.admin.monteeq.com", + "https://monteeqorg-backend.hf.space", + "http://localhost:5173", + "http://localhost:5174", + ], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Mount static files +static_path = os.path.join(os.path.dirname(__file__), "static") +os.makedirs(static_path, exist_ok=True) +app.mount("/static", StaticFiles(directory=static_path), name="static") + +# ── Global Exception Handlers ──────────────────────────────────────────────── +register_exception_handlers(app) + +# ── Routers ─────────────────────────────────────────────────────────────────── +app.include_router(api_router, prefix="/api/v1") +app.include_router(seo.router) + + +# ── WebSocket Chat Endpoint ─────────────────────────────────────────────────── +from app.core.ws_manager import manager as ws_manager + +@app.websocket("/ws/chat") +async def websocket_chat(websocket: WebSocket, token: str = Query(...)): + """Authenticated WebSocket for real-time chat message push.""" + from jose import jwt, JWTError + from app.core.config import SECRET_KEY, ALGORITHM + from app.db.session import SessionLocal + from app.models.models import User + + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username = payload.get("sub") + if not username: + await websocket.close(code=4001) + return + except JWTError: + await websocket.close(code=4001) + return + + db = SessionLocal() + try: + user = db.query(User).filter(User.username == username).first() + if not user: + await websocket.close(code=4001) + return + finally: + db.close() + + await ws_manager.connect(user.id, websocket) + try: + while True: + # Keep-alive: client sends periodic pings, we just read and discard + await websocket.receive_text() + except WebSocketDisconnect: + ws_manager.disconnect(user.id, websocket) + except Exception: + ws_manager.disconnect(user.id, websocket) + + +# ── Initialization ──────────────────────────────────────────────────────────── +@app.on_event("startup") +async def startup(): + from app.core.config import REDIS_URL + redis = aioredis.from_url(REDIS_URL, encoding="utf8", decode_responses=True) + FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache") + +@app.get("/", tags=["System"]) +async def root_health(): + """Default root endpoint for simple load balancer health checks.""" + return {"status": "ok", "message": "Monteeq Backend API is running"} + +@app.get("/health", tags=["System"]) +async def health_check(): + """Simple liveness probe used by load balancers and uptime monitors.""" + return JSONResponse( + status_code=200, + content={"status": "ok", "service": "monteeq-backend"}, + ) diff --git a/migrate_categories.py b/migrate_categories.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf8a02ff6cde0a729a044d2c9800fd86b2bbc50 --- /dev/null +++ b/migrate_categories.py @@ -0,0 +1,7 @@ +"""Run this script to create the discovered_categories table.""" +import sys +sys.path.insert(0, ".") +from app.db.session import engine +from app.models.models import DiscoveredCategory +DiscoveredCategory.__table__.create(engine, checkfirst=True) +print("✅ discovered_categories table created successfully") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3fd8f59d3d9acafb0a84d84eecc9f3ce67619b9e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,29 @@ +fastapi[all] +uvicorn +python-dotenv +python-jose[cryptography] +passlib[bcrypt] +bcrypt==3.2.2 +python-multipart +pydantic +pydantic-settings +requests +google-auth +httpx +psycopg2-binary +sqlalchemy[asyncio] +asyncpg +pywebpush +alembic +aiofiles +pyotp +qrcode +Pillow +celery +redis +boto3 +orjson +brotli +fastapi-cache2[redis] +tenacity +stripe diff --git a/route_return_check.py b/route_return_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5a03575c1ac0f5e055ffbb9df733ca3819f34b9c --- /dev/null +++ b/route_return_check.py @@ -0,0 +1,55 @@ +import ast +from pathlib import Path +root = Path('app/api/v1/endpoints') +route_funcs = [] + +for path in sorted(root.rglob('*.py')): + text = path.read_text(encoding='utf-8') + try: + tree = ast.parse(text) + except Exception as e: + print('PARSE ERROR', path, e) + continue + + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + for dec in node.decorator_list: + if isinstance(dec, ast.Attribute) and isinstance(dec.value, ast.Name) and dec.value.id == 'router' and dec.attr in {'get','post','put','delete','patch','options','head'}: + route_funcs.append((path, node.name, node.lineno, node)) + break + + +def ends_with_return(node): + if not node.body: + return False + last = node.body[-1] + if isinstance(last, (ast.Return, ast.Raise)): + return True + # if last statement is if/for/while/try, check all branches + if isinstance(last, ast.If): + return ends_with_return(last) # using helper below + if isinstance(last, (ast.For, ast.While, ast.AsyncFor)): + return False + if isinstance(last, ast.Try): + return False + return False + + +def ends_with_return(stmt): + if isinstance(stmt, (ast.Return, ast.Raise)): + return True + if isinstance(stmt, ast.If): + if not stmt.body or not stmt.orelse: + return False + return ends_with_return(stmt.body[-1]) and ends_with_return(stmt.orelse[-1]) + if isinstance(stmt, ast.Try): + handlers = stmt.handlers + if not stmt.finalbody or not handlers: + return False + return ends_with_return(stmt.body[-1]) and all(ends_with_return(h.body[-1]) for h in handlers) and ends_with_return(stmt.finalbody[-1]) + return False + +for path, name, lineno, node in route_funcs: + if not ends_with_return(node): + print('POSSIBLE', path, name, lineno) +print('TOTAL ROUTES', len(route_funcs)) diff --git a/scan_missing_returns.py b/scan_missing_returns.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e5d737b8dd3860703ba4e6efd76fd57909cde3 --- /dev/null +++ b/scan_missing_returns.py @@ -0,0 +1,22 @@ +import ast +from pathlib import Path +root = Path('app/api/v1/endpoints') +for path in sorted(root.rglob('*.py')): + text = path.read_text(encoding='utf-8') + try: + tree = ast.parse(text) + except Exception as e: + print('PARSE ERROR', path, e) + continue + for node in ast.walk(tree): + if isinstance(node, ast.AsyncFunctionDef): + has_router = False + for dec in node.decorator_list: + if isinstance(dec, ast.Attribute) and isinstance(dec.value, ast.Name) and dec.value.id == 'router' and dec.attr in {'get','post','put','delete','patch','options','head'}: + has_router = True + break + if not has_router: + continue + has_return = any(isinstance(sub, (ast.Return, ast.Raise)) for sub in ast.walk(node)) + if not has_return: + print('MISSING', path, node.name, node.lineno) diff --git a/scripts/deploy_ecr.sh b/scripts/deploy_ecr.sh new file mode 100644 index 0000000000000000000000000000000000000000..70b3004cf65b3ee3b6adac8192e7859a1d5f1c3a --- /dev/null +++ b/scripts/deploy_ecr.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# Script to build and push backend image to Amazon ECR + +# Exit immediately if a command exits with a non-zero status +set -e + +# Configuration variables (Modify these to match your AWS environment) +AWS_REGION="${AWS_REGION:-us-west-2}" +AWS_ACCOUNT_ID="${AWS_ACCOUNT_ID:-037302670720}" +REPO_NAME="${REPO_NAME:-monteeq}" +IMAGE_TAG="${IMAGE_TAG:-latest}" + +ECR_URL="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com" + +echo "------------------------------------------------" +echo "🚀 Preparing ECR deployment for ${REPO_NAME}" +echo "📍 Region: ${AWS_REGION}" +echo "📍 ECR URL: ${ECR_URL}" +echo "------------------------------------------------" + +# Resolve aws CLI binary path +AWS_CLI="aws" +if ! command -v aws &> /dev/null; then + if [ -f "$HOME/bin/aws" ]; then + AWS_CLI="$HOME/bin/aws" + else + echo "❌ Error: aws CLI command not found. Please install it or add it to PATH." + exit 1 + fi +fi + +# Detect if docker requires sudo +DOCKER_CMD="docker" +if ! docker info &>/dev/null; then + DOCKER_CMD="sudo docker" + echo "⚠️ Note: Current user lacks Docker socket permissions. Using 'sudo docker' for container operations." +fi + +# Step 1: Login to ECR +echo "🔐 Logging into Amazon ECR..." +${AWS_CLI} ecr get-login-password --region "${AWS_REGION}" | ${DOCKER_CMD} login --username AWS --password-stdin "${ECR_URL}" + +# Step 2: Create ECR repository if it doesn't exist +echo "📦 Checking/creating repository ${REPO_NAME} in ECR..." +${AWS_CLI} ecr describe-repositories --repository-names "${REPO_NAME}" --region "${AWS_REGION}" >/dev/null 2>&1 || \ + ${AWS_CLI} ecr create-repository --repository-name "${REPO_NAME}" --region "${AWS_REGION}" + +# Step 3: Build Docker Image +echo "🏗️ Building Docker image..." +# Run build from backend directory +cd "$(dirname "$0")/.." +${DOCKER_CMD} build -t "${REPO_NAME}" . + +# Step 4: Tag Image +echo "🏷️ Tagging image..." +${DOCKER_CMD} tag "${REPO_NAME}:latest" "${ECR_URL}/${REPO_NAME}:${IMAGE_TAG}" + +# Step 5: Push Image to ECR +echo "🚀 Pushing image to ECR..." +${DOCKER_CMD} push "${ECR_URL}/${REPO_NAME}:${IMAGE_TAG}" + +echo "------------------------------------------------" +echo "✅ Deployment image successfully pushed to ECR!" +echo "🐳 Image URI: ${ECR_URL}/${REPO_NAME}:${IMAGE_TAG}" +echo "------------------------------------------------" diff --git a/scripts/seed_db.py b/scripts/seed_db.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4a679f9db89db1dd99c558f53448eb4c3f878b --- /dev/null +++ b/scripts/seed_db.py @@ -0,0 +1,61 @@ +import sys +import os + +# Add backend directory to path +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from sqlalchemy.orm import Session +from app.db.session import SessionLocal +from app.models.models import User, Video, Post +from app.core.security import get_password_hash + +def seed(): + db = SessionLocal() + try: + # Create a test user if not exists + admin_user = db.query(User).filter(User.username == "icedmist").first() + if not admin_user: + print("Creating test user: icedmist") + admin_user = User( + username="icedmist", + email="talk2icedmist@gmail.com", + full_name="Iced Mist", + hashed_password=get_password_hash("Monteeq2026!"), + role="admin", + is_verified=True, + is_onboarded=True + ) + db.add(admin_user) + db.commit() + db.refresh(admin_user) + else: + # Ensure existing test user is verified and onboarded to avoid loops + admin_user.is_verified = True + admin_user.is_onboarded = True + db.commit() + + # Create a sample video + video_count = db.query(Video).count() + if video_count == 0: + print("Creating sample video...") + video = Video( + title="Cinematic Monteeq Intro", + description="Experience the future of video platforms.", + video_url="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", + thumbnail_url="https://images.unsplash.com/photo-1492144534655-ae79c964c9d7?auto=format&fit=crop&q=80", + video_type="home", + status="approved", + owner_id=admin_user.id + ) + db.add(video) + db.commit() + + print("Database seeded successfully!") + except Exception as e: + print(f"Error seeding database: {e}") + db.rollback() + finally: + db.close() + +if __name__ == "__main__": + seed() diff --git a/scripts/seed_demo_flash.py b/scripts/seed_demo_flash.py new file mode 100644 index 0000000000000000000000000000000000000000..41d1826d8c4cf1a634505208612532e13aac7694 --- /dev/null +++ b/scripts/seed_demo_flash.py @@ -0,0 +1,113 @@ +import os +import sys +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from datetime import datetime + +# Adjust path to import models +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +from app.models.models import Video, User, ApprovalStatus, VideoType +from app.core.config import DATABASE_URL + +engine = create_engine(DATABASE_URL) +SessionLocal = sessionmaker(bind=engine) + +DEMO_VIDEOS = [ + { + "title": "Elite Football Skills", + "description": "Unbelievable ball control in the tightest spaces. #football #skills", + "video_url": "https://player.vimeo.com/external/384738719.sd.mp4?s=38290ef43f65e2524fb72d4ecf97f7e9f3b610c1&profile_id=165", + "thumbnail_url": "https://images.pexels.com/photos/3074920/pexels-photo-3074920.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1", + "tags": "football,football edit,sports", + "duration": 15 + }, + { + "title": "Neon City Drift AMV", + "description": "Synthwave vibes and high-octane anime action. #amv #anime #drift", + "video_url": "https://player.vimeo.com/external/459389133.sd.mp4?s=1d59663738092f6ceef5d654f59fc93374246ed8&profile_id=165", + "thumbnail_url": "https://images.pexels.com/photos/1111319/pexels-photo-1111319.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1", + "tags": "amv,anime,neon", + "duration": 12 + }, + { + "title": "Cyberpunk Gaming Highlights", + "description": "Pre-fire and precision movements. #gaming #fps #cyberpunk", + "video_url": "https://player.vimeo.com/external/391054941.sd.mp4?s=d009e4a3ed609f874c76899e9929f6b9076f254b&profile_id=165", + "thumbnail_url": "https://images.pexels.com/photos/7915234/pexels-photo-7915234.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1", + "tags": "gaming,tactical,fps", + "duration": 18 + }, + { + "title": "Tactical CQB Training", + "description": "Close quarters mastery. High speed, low drag. #tactical #training", + "video_url": "https://player.vimeo.com/external/517614057.sd.mp4?s=1246c4f9f743c3968603681436573c7f9996d99e&profile_id=165", + "thumbnail_url": "https://images.pexels.com/photos/4429511/pexels-photo-4429511.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1", + "tags": "tactical,training,mil", + "duration": 20 + }, + { + "title": "Vintage Anime Aesthetic", + "description": "Lofi hip hop beats to relax/study to. #anime #lofi #aesthetic", + "video_url": "https://player.vimeo.com/external/415410118.sd.mp4?s=17f41f021ad2db6a2a07c11b0e071725b827e857&profile_id=165", + "thumbnail_url": "https://images.pexels.com/photos/356079/pexels-photo-356079.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1", + "tags": "anime,lofi,vibes", + "duration": 25 + } +] + +def seed(): + db = SessionLocal() + try: + # 1. Create/Get Demo User + demo_user = db.query(User).filter(User.username == "monteeq_demo").first() + if not demo_user: + demo_user = User( + username="monteeq_demo", + email="demo@monteeq.com", + full_name="Monteeq Demo", + is_verified=True, + is_onboarded=True, + profile_pic="https://ui-avatars.com/api/?name=Monteeq+Demo&background=FF3B30&color=fff" + ) + db.add(demo_user) + db.commit() + db.refresh(demo_user) + print(f"Created demo user: {demo_user.username}") + else: + print(f"Using existing demo user: {demo_user.username}") + + # 2. Add Videos + for v_data in DEMO_VIDEOS: + existing = db.query(Video).filter(Video.video_url == v_data["video_url"]).first() + if not existing: + video = Video( + title=v_data["title"], + description=v_data["description"], + video_url=v_data["video_url"], + thumbnail_url=v_data["thumbnail_url"], + video_type=VideoType.FLASH, + status=ApprovalStatus.APPROVED, + owner_id=demo_user.id, + tags=v_data["tags"], + duration=v_data["duration"], + views=0, + likes_count=0, + comments_count=0 + ) + db.add(video) + print(f"Added video: {v_data['title']}") + else: + print(f"Video already exists: {v_data['title']}") + + db.commit() + print("Seeding completed successfully!") + + except Exception as e: + db.rollback() + print(f"Error during seeding: {e}") + finally: + db.close() + +if __name__ == "__main__": + seed() diff --git a/scripts/wipe_videos.py b/scripts/wipe_videos.py new file mode 100644 index 0000000000000000000000000000000000000000..ce31d6d701512466a4ee066241721cec1f2b1b9a --- /dev/null +++ b/scripts/wipe_videos.py @@ -0,0 +1,82 @@ +import os +import sys + +# Add backend directory to Python path +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +from app.db.session import SessionLocal +from app.models.models import Video, VideoInteraction, Like, Comment, View, WatchLater, Repost, ChallengeEntry, Challenge, User +from app.core.storage import storage + +def delete_all_videos(): + db = SessionLocal() + try: + videos = db.query(Video).all() + print(f"Found {len(videos)} videos in database. Deleting metadata and S3 files...") + + # Clear S3 directories + print("Clearing S3 prefix 'uploads/'...") + storage.delete_prefix("uploads/") + print("Clearing S3 prefix 'videos/'...") + storage.delete_prefix("videos/") + print("Clearing S3 prefix 'thumbnails/'...") + storage.delete_prefix("thumbnails/") + print("Clearing S3 prefix 'thumbs/'...") + storage.delete_prefix("thumbs/") + + print("Deleting video metadata from database...") + + # Helper function to delete safely + def safe_delete(model, filter_cond=None): + try: + query = db.query(model) + if filter_cond is not None: + query = query.filter(filter_cond) + query.delete() + except Exception as ex: + db.rollback() + print(f"Skipping {model.__tablename__}: {ex}") + + # Reset Challenge entry counts + challenges = db.query(Challenge).all() + for c in challenges: + c.entry_count = 0 + + # Delete dependent records + safe_delete(VideoInteraction) + safe_delete(WatchLater) + safe_delete(Repost, Repost.video_id.isnot(None)) + safe_delete(ChallengeEntry, ChallengeEntry.video_id.isnot(None)) + safe_delete(Like, Like.video_id.isnot(None)) + + # For comments, handle self-referential replies before deleting root comments + try: + db.query(Comment).filter(Comment.video_id.isnot(None), Comment.parent_id.isnot(None)).delete() + db.query(Comment).filter(Comment.video_id.isnot(None)).delete() + except Exception as ex: + db.rollback() + print(f"Skipping comments: {ex}") + + safe_delete(View, View.video_id.isnot(None)) + + # Finally delete videos + safe_delete(Video) + + # Reset user upload counts + try: + db.query(User).update({"flash_uploads": 0, "home_uploads": 0}) + except Exception as ex: + db.rollback() + pass + + db.commit() + print("✅ Successfully deleted all videos, associated metadata, and S3 files.") + + except Exception as e: + db.rollback() + print(f"❌ Error: {e}") + finally: + db.close() + +if __name__ == "__main__": + delete_all_videos() diff --git a/send_test_emails.py b/send_test_emails.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd76a69569fff205011db8912142843ca6da5b8 --- /dev/null +++ b/send_test_emails.py @@ -0,0 +1,94 @@ +""" +Send one of every email type to smasduqacc@gmail.com. +Run from: backend/ → source .venv/bin/activate && python send_test_emails.py +""" +import os, sys +from dotenv import load_dotenv +load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) + +from app.services.email_service import ( + send_verification_email, + send_password_reset_email, + send_pro_upgrade_email, + send_challenge_announcement_batch, + send_challenge_exit_email, + send_welcome_email, + send_day3_nudge_email, + send_first_video_email, + send_first_follower_email, + send_first_like_email, + send_weekly_digest_email, + send_monthly_stats_email, + send_reengagement_email, + send_challenge_ending_soon_email, + send_challenge_result_email, + send_security_email, + send_subscription_email, + send_first_comment_email, + send_mention_email, + send_growth_drip_email, + send_celebration_email, + send_social_batch_email, +) + +TO = "smasduqacc@gmail.com" +BCC = [TO] + +SAMPLE_VIDEOS = [ + {"title": "Dubai Cinematic Edit", "creator": "@darkframe", "url": "https://monteeq.com/v/1"}, + {"title": "BMPCC Color Grade Reel", "creator": "@colorist_k", "url": "https://monteeq.com/v/2"}, + {"title": "Speed Ramp Showreel 2026", "creator": "@rampgod", "url": "https://monteeq.com/v/3"}, + {"title": "Minimal Title Motion", "creator": "@typemotion", "url": "https://monteeq.com/v/4"}, + {"title": "Anamorphic Street Edit", "creator": "@lensflare", "url": "https://monteeq.com/v/5"}, +] + +SAMPLE_STATS = {"views": 4821, "likes": 312, "followers": 47, "uploads": 6} + +tests = [ + ("Verification", lambda: send_verification_email(TO, "847291")), + ("Password Reset", lambda: send_password_reset_email(TO, "tok_abc123xyz")), + ("Pro Upgrade", lambda: send_pro_upgrade_email(TO, "smasduq")), + ("Challenge Announcement", lambda: send_challenge_announcement_batch(BCC, "The Creator Showdown", "$500", "June 30, 2026")), + ("Challenge Exit", lambda: send_challenge_exit_email(TO, "smasduq", "The Creator Showdown")), + ("Welcome", lambda: send_welcome_email(TO, "smasduq")), + ("Day-3 Nudge", lambda: send_day3_nudge_email(TO, "smasduq")), + ("First Video", lambda: send_first_video_email(TO, "smasduq", "Dubai Cinematic Edit", "https://monteeq.com/v/1")), + ("First Follower", lambda: send_first_follower_email(TO, "smasduq", "darkframe")), + ("First Like", lambda: send_first_like_email(TO, "smasduq", "Dubai Cinematic Edit", "darkframe", "https://monteeq.com/v/1")), + ("Weekly Digest", lambda: send_weekly_digest_email(BCC, SAMPLE_VIDEOS)), + ("Monthly Stats", lambda: send_monthly_stats_email(TO, "smasduq", "May", SAMPLE_STATS)), + ("Re-engagement", lambda: send_reengagement_email(TO, "smasduq")), + ("Challenge Ending Soon", lambda: send_challenge_ending_soon_email(BCC, "The Creator Showdown", "$500", "June 30, 2026")), + ("Challenge Result", lambda: send_challenge_result_email(BCC, "The Creator Showdown", "darkframe", "https://monteeq.com/v/1", "$500")), + # New Sprint 2 & 3 tests + ("Security (New Device)", lambda: send_security_email(TO, "new_device_login", "smasduq", device_info="MacBook Pro", ip_address="192.168.1.1", location="London, UK")), + ("Security (PW Changed)", lambda: send_security_email(TO, "password_changed", "smasduq", timestamp="2026-06-04")), + ("Subscription (Started)", lambda: send_subscription_email(TO, "trial_started", "smasduq")), + ("Subscription (Ending)", lambda: send_subscription_email(TO, "trial_ending", "smasduq", expiry_date="June 10, 2026")), + ("First Comment", lambda: send_first_comment_email(TO, "smasduq", "Dubai Cinematic Edit", "darkframe", "Great pacing, keep it up!", "https://monteeq.com/v/1")), + ("Mention", lambda: send_mention_email(TO, "smasduq", "darkframe", "Check out @smasduq's street edit, clean ramps!", "https://monteeq.com/v/1")), + ("Growth Drip (Week 1)", lambda: send_growth_drip_email(TO, "smasduq", 1)), + ("Celebration (Anniversary)", lambda: send_celebration_email(TO, "smasduq", "welcome_anniversary")), + ("Social Batch Recap", lambda: send_social_batch_email(TO, "smasduq", "- 3 new followers\n- 12 new likes on your edits\n- 2 new comments on your videos")), +] + +print(f"\n{'─'*52}") +print(f" Sending {len(tests)} emails to {TO}") +print(f"{'─'*52}\n") + +results = {} +for name, fn in tests: + try: + ok = fn() + results[name] = ok + print(f" [{'OK ' if ok else 'FAIL'}] {name}") + except Exception as e: + results[name] = False + print(f" [ERR ] {name} → {type(e).__name__}: {e}") + +passed = sum(results.values()) +total = len(results) +print(f"\n{'─'*52}") +print(f" {passed}/{total} sent successfully.") +print(f"{'─'*52}\n") +sys.exit(0 if passed == total else 1) diff --git a/start.sh b/start.sh new file mode 100644 index 0000000000000000000000000000000000000000..2501f3084b1598c6b3c67c6353d959dd535bfcf7 --- /dev/null +++ b/start.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e + +echo "Starting Celery worker in background..." +celery -A app.worker.celery_app worker \ + --loglevel=info \ + --concurrency=2 \ + --pool=solo & + +echo "Starting Celery beat scheduler in background..." +celery -A app.worker.celery_app beat \ + --loglevel=info & + +echo "Starting FastAPI server on port 7860..." +exec uvicorn main:app --host 0.0.0.0 --port 7860 --workers 1