Monteeq CI commited on
Commit
3533fb9
Β·
1 Parent(s): 1905a15

πŸš€ Initial deployment of Monteeq backend

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