diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..aa5eeed --- /dev/null +++ b/alembic.ini @@ -0,0 +1,149 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +# sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/alembic/README b/alembic/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..f48244c --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,86 @@ + +import os +import sys +from logging.config import fileConfig + +from sqlalchemy import engine_from_config, pool + +from alembic import context + +# Добавляем корень проекта в sys.path, чтобы импортировать твои модули +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) + +# Импортируем твой Base и настройки +from core.config import settings # Если у тебя настройки в Pydantic +from core.db import Base + +# Импортируй ВСЕ модели, чтобы Alembic их увидел +from models import audio_model, photo_model, video_model + +# (или как у тебя называется файл, где лежат все модели) + +# this is the Alembic Config object +config = context.config + +# Устанавливаем URL базы данных из твоих настроек +config.set_main_option("sqlalchemy.url", settings.database_url) + +# ... дальше идет стандартный код ... +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/alembic/versions/edca9d8e52b5_initial_migration.py b/alembic/versions/edca9d8e52b5_initial_migration.py new file mode 100644 index 0000000..635bbfc --- /dev/null +++ b/alembic/versions/edca9d8e52b5_initial_migration.py @@ -0,0 +1,42 @@ +"""Initial migration + +Revision ID: edca9d8e52b5 +Revises: +Create Date: 2026-11-07 19:23:14.677545 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'edca9d8e52b5' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_table('users') + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('users', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('username', sa.VARCHAR(length=128), autoincrement=False, nullable=False), + sa.Column('hashed_password', sa.VARCHAR(length=255), autoincrement=False, nullable=False), + sa.Column('isAdmin', sa.BOOLEAN(), autoincrement=False, nullable=False), + sa.PrimaryKeyConstraint('id', name=op.f('users_pkey')) + ) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + # ### end Alembic commands ### diff --git a/core/authx.py b/core/authx.py index 0fee7ef..23b85f9 100644 --- a/core/authx.py +++ b/core/authx.py @@ -1,6 +1,5 @@ from authx import AuthX, AuthXConfig - -from .config import settings +from core.config import settings config = AuthXConfig( JWT_SECRET_KEY=settings.SECRET_KEY, diff --git a/core/config.py b/core/config.py index 6c39744..9110f9c 100644 --- a/core/config.py +++ b/core/config.py @@ -2,6 +2,7 @@ import os from pathlib import Path from dotenv import load_dotenv +from pydantic_settings import BaseSettings, SettingsConfigDict BASE_DIR = Path(__file__).resolve().parent.parent @@ -24,10 +25,22 @@ AUDIO_DIR = BASE_DIR / "media" / "audio" COVERS = "_covers" COVERS_DIR = AUDIO_DIR / COVERS -from pydantic_settings import BaseSettings +DB_PASSWORD = os.getenv("DB_PASSWORD") +DB_USER = os.getenv("DB_USER") +DB_NAME = os.getenv("DB_NAME") + +DB_URL = f"postgresql+psycopg://{DB_USER}:{DB_PASSWORD}@127.0.0.1:5432/{DB_NAME}" class Settings(BaseSettings): + + model_config = SettingsConfigDict(env_file=".env", extra="ignore") # лучше ignore + + # Добавь то, что есть в .env + DB_USER: str + DB_PASSWORD: str + DB_NAME: str + SECRET_KEY: str = os.getenv("SECRET_KEY") ALGORITHM: str = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 @@ -35,8 +48,9 @@ class Settings(BaseSettings): COOKIE_SECURE: bool = False COOKIE_SAMESITE: str = "lax" COOKIE_DOMAIN: str | None = None + @property + def database_url(self) -> str: + return f"postgresql+psycopg://{self.DB_USER}:{self.DB_PASSWORD}@127.0.0.1:5432/{self.DB_NAME}" - class Config: - env_file = ".env" settings = Settings() \ No newline at end of file diff --git a/core/db.py b/core/db.py index 7421102..18aba73 100644 --- a/core/db.py +++ b/core/db.py @@ -1,6 +1,3 @@ -import os - -from dotenv import load_dotenv from sqlalchemy.ext.asyncio import ( AsyncSession, async_sessionmaker, @@ -8,20 +5,12 @@ from sqlalchemy.ext.asyncio import ( ) from sqlalchemy.orm import DeclarativeBase -from .config import BASE_DIR +from .config import DB_URL class Base(DeclarativeBase): pass -dotenv_path = BASE_DIR / '.env' -load_dotenv(dotenv_path=dotenv_path) - -DB_PASSWORD = os.getenv("DB_PASSWORD") -DB_USER = os.getenv("DB_USER") -DB_NAME = os.getenv("DB_NAME") - -DB_URL = f"postgresql+psycopg://{DB_USER}:{DB_PASSWORD}@127.0.0.1:5432/{DB_NAME}" engine = create_async_engine(DB_URL, echo=True) diff --git a/main.py b/main.py index 5f17640..1bf04a5 100644 --- a/main.py +++ b/main.py @@ -5,7 +5,7 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles -from .core.config import ( +from core.config import ( AUDIO_DIR, COVERS_DIR, PHOTOS_DIR_RESPNS, @@ -13,9 +13,9 @@ from .core.config import ( THUMBS_DIR, YT_DIR, ) -from .core.db import Base, engine -from .routers import audio, auth, channel, photo, playlist, search, video -from .search.setup import setup_videos_index +from core.db import Base, engine +from routers import audio, auth, channel, photo, playlist, search, video +from search.setup import setup_videos_index @asynccontextmanager @@ -41,11 +41,17 @@ app.add_middleware( app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") -app.mount("/yt", StaticFiles(directory=YT_DIR), name="yt") -app.mount("/media", StaticFiles(directory=PHOTOS_DIR_RESPNS), name="media") -app.mount("/_thumbs", StaticFiles(directory=THUMBS_DIR), name="_thumbs") -app.mount("/_covers", StaticFiles(directory=COVERS_DIR), name="_covers") -app.mount("/audio", StaticFiles(directory=AUDIO_DIR), name="audio") + +try: + app.mount("/yt", StaticFiles(directory=YT_DIR), name="yt") + app.mount("/media", StaticFiles(directory=PHOTOS_DIR_RESPNS), name="media") + app.mount("/_thumbs", StaticFiles(directory=THUMBS_DIR), name="_thumbs") + app.mount("/_covers", StaticFiles(directory=COVERS_DIR), name="_covers") + app.mount("/audio", StaticFiles(directory=AUDIO_DIR), name="audio") + +except RuntimeError as err: + ValueError(err) + @app.get("/favicon.ico", include_in_schema=False) async def favicon(): diff --git a/models/__init__.py b/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/audio_model.py b/models/audio_model.py index 6e777c8..fa425cb 100644 --- a/models/audio_model.py +++ b/models/audio_model.py @@ -1,7 +1,7 @@ from sqlalchemy import ForeignKey, String from sqlalchemy.orm import Mapped, mapped_column, relationship -from ..core.db import Base +from core.db import Base class AudioPlaylist(Base): diff --git a/models/photo_model.py b/models/photo_model.py index 712be89..9825b50 100644 --- a/models/photo_model.py +++ b/models/photo_model.py @@ -3,7 +3,7 @@ from __future__ import annotations from sqlalchemy import ForeignKey, String from sqlalchemy.orm import Mapped, mapped_column, relationship -from ..core.db import Base +from core.db import Base class Category(Base): diff --git a/models/users.py b/models/users.py index 83d3e60..9a8d9a2 100644 --- a/models/users.py +++ b/models/users.py @@ -1,7 +1,7 @@ from sqlalchemy import Integer, String from sqlalchemy.orm import Mapped, mapped_column -from ..core.db import Base +from core.db import Base class User(Base): diff --git a/models/video_model.py b/models/video_model.py index bd66089..43c17d5 100644 --- a/models/video_model.py +++ b/models/video_model.py @@ -3,7 +3,7 @@ from datetime import date from sqlalchemy import Date, ForeignKey, String, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship -from ..core.db import Base +from core.db import Base class Channel(Base): diff --git a/routers/__init__.py b/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/routers/audio.py b/routers/audio.py index 9f415ea..a61c511 100644 --- a/routers/audio.py +++ b/routers/audio.py @@ -5,10 +5,10 @@ from fastapi.exceptions import HTTPException from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from ..core.authx import auth -from ..core.db import get_db -from ..models.audio_model import Audio, AudioPlaylist -from ..schemas.audio_schema import Audios, AudioSchema, Playlists +from core.authx import auth +from core.db import get_db +from models.audio_model import Audio, AudioPlaylist +from schemas.audio_schema import Audios, AudioSchema, Playlists router = APIRouter() diff --git a/routers/auth.py b/routers/auth.py index 336b75e..4c8232a 100644 --- a/routers/auth.py +++ b/routers/auth.py @@ -2,11 +2,11 @@ from fastapi import APIRouter, Depends, HTTPException, Request, Response from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from ..core.authx import auth -from ..core.db import get_db -from ..core.security import hash_password, verify_password -from ..models.users import User -from ..schemas.user_schema import UserCreate, UserLogin, UserRead +from core.authx import auth +from core.db import get_db +from core.security import hash_password, verify_password +from models.users import User +from schemas.user_schema import UserCreate, UserLogin, UserRead router = APIRouter(prefix="/auth", tags=["auth"]) diff --git a/routers/channel.py b/routers/channel.py index dc180e8..cdfd466 100644 --- a/routers/channel.py +++ b/routers/channel.py @@ -3,11 +3,11 @@ from fastapi.templating import Jinja2Templates from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from ..core.authx import auth -from ..core.config import TEMPLATES_DIR -from ..core.db import get_db -from ..models.video_model import Channel, Playlist, Video -from ..schemas.channel_schemas import ChannelOut, ChannelsOut +from core.authx import auth +from core.config import TEMPLATES_DIR +from core.db import get_db +from models.video_model import Channel, Playlist, Video +from schemas.channel_schemas import ChannelOut, ChannelsOut router = APIRouter() templates = Jinja2Templates(directory=TEMPLATES_DIR) diff --git a/routers/photo.py b/routers/photo.py index 9454225..d5969de 100644 --- a/routers/photo.py +++ b/routers/photo.py @@ -2,10 +2,10 @@ from fastapi import APIRouter, Depends, Query from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from ..core.authx import auth -from ..core.db import get_db -from ..models.photo_model import Category, Photo -from ..schemas.photo_schemas import CategoriesOut, PhotosOut, PhotosPaginatedOut +from core.authx import auth +from core.db import get_db +from models.photo_model import Category, Photo +from schemas.photo_schemas import CategoriesOut, PhotosOut, PhotosPaginatedOut router = APIRouter() diff --git a/routers/playlist.py b/routers/playlist.py index b345db5..49e2b10 100644 --- a/routers/playlist.py +++ b/routers/playlist.py @@ -3,11 +3,11 @@ from fastapi.templating import Jinja2Templates from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from ..core.authx import auth -from ..core.config import TEMPLATES_DIR -from ..core.db import get_db -from ..models.video_model import Video -from ..schemas.playlist_schema import PlaylistOut +from core.authx import auth +from core.config import TEMPLATES_DIR +from core.db import get_db +from models.video_model import Video +from schemas.playlist_schema import PlaylistOut router = APIRouter() templates = Jinja2Templates(directory=TEMPLATES_DIR) diff --git a/routers/search.py b/routers/search.py index 9e80117..1c8ac68 100644 --- a/routers/search.py +++ b/routers/search.py @@ -3,7 +3,7 @@ from fastapi import APIRouter, Query from fastapi.concurrency import run_in_threadpool from pydantic import BaseModel -from ..search.search_client import videos_index +from search.search_client import videos_index router = APIRouter(prefix="/search", tags=["search"]) diff --git a/routers/video.py b/routers/video.py index 896b2c6..4643f03 100644 --- a/routers/video.py +++ b/routers/video.py @@ -5,10 +5,10 @@ from fastapi.exceptions import HTTPException from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from ..core.authx import auth -from ..core.db import get_db -from ..models.video_model import Channel, Video -from ..schemas.video_schemas import VideoDetailOut, VideoOut, VideosResponse +from core.authx import auth +from core.db import get_db +from models.video_model import Channel, Video +from schemas.video_schemas import VideoDetailOut, VideoOut, VideosResponse router = APIRouter() diff --git a/schemas/__init__.py b/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/schemas/audio_schema.py b/schemas/audio_schema.py index 08d2e4b..7ef811d 100644 --- a/schemas/audio_schema.py +++ b/schemas/audio_schema.py @@ -1,6 +1,6 @@ from pydantic import BaseModel, ConfigDict, field_validator -from ..services.path import encode_path +from services.path import encode_path class AudioSchema(BaseModel): diff --git a/schemas/channel_schemas.py b/schemas/channel_schemas.py index 471b702..ca9c34f 100644 --- a/schemas/channel_schemas.py +++ b/schemas/channel_schemas.py @@ -2,7 +2,7 @@ from datetime import date as DateType from pydantic import BaseModel, field_validator -from ..services.path import encode_path +from services.path import encode_path class ChannelItem(BaseModel): diff --git a/schemas/photo_schemas.py b/schemas/photo_schemas.py index 529743f..72d2711 100644 --- a/schemas/photo_schemas.py +++ b/schemas/photo_schemas.py @@ -2,7 +2,7 @@ from __future__ import annotations from pydantic import BaseModel, ConfigDict, field_validator -from ..services.path import encode_path +from services.path import encode_path class PhotoItem(BaseModel): diff --git a/schemas/playlist_schema.py b/schemas/playlist_schema.py index 51f5c14..7b0f60b 100644 --- a/schemas/playlist_schema.py +++ b/schemas/playlist_schema.py @@ -2,7 +2,7 @@ from datetime import date as DateType from pydantic import BaseModel, field_validator -from ..services.path import encode_path +from services.path import encode_path class VideoItem(BaseModel): diff --git a/schemas/video_schemas.py b/schemas/video_schemas.py index 564557c..afaa07f 100644 --- a/schemas/video_schemas.py +++ b/schemas/video_schemas.py @@ -2,7 +2,7 @@ from datetime import date as DateType from pydantic import BaseModel, ConfigDict, field_validator -from ..services.path import encode_path +from services.path import encode_path class VideoOut(BaseModel): diff --git a/search/__init__.py b/search/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/search/search_client.py b/search/search_client.py index 242e780..1e7c773 100644 --- a/search/search_client.py +++ b/search/search_client.py @@ -3,7 +3,7 @@ import os import meilisearch from dotenv import load_dotenv -from ..core.config import BASE_DIR +from core.config import BASE_DIR load_dotenv(BASE_DIR / '.env')