Skip to content

Commit

Permalink
Merge pull request #15 from MutilatedPeripherals/deploy
Browse files Browse the repository at this point in the history
Deploy
  • Loading branch information
lmeullibre authored Dec 1, 2024
2 parents f38cc04 + 2b05cdf commit 851c958
Show file tree
Hide file tree
Showing 59 changed files with 526 additions and 365 deletions.
File renamed without changes.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# controltab

## Relevant Links:
- [Backend Swagger Docs](https://backend-production-0646.up.railway.app/docs)
- [Landing Page Prototype](https://yj8u03csybl1ve8pzinpqlhohn3qabuu.vercel.app)

## Backend setup

```bash
Expand Down Expand Up @@ -29,7 +33,7 @@ npm install
npm run dev
```

TODOs:
## TODOs:
* when we accept a change, then also save the history of the previous version.
* when we have the history available in the db, then provide a rollback functionality.
* what do we do with dangling files. we should have a scheduler which checks that any file not being a part of a history gets deleted or sth.
Expand Down
2 changes: 1 addition & 1 deletion diffing/.gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.pytest_cache
__pycache__
.idea
../.idea
.env
files
tmp
21 changes: 21 additions & 0 deletions diffing/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Backend Dockerfile
FROM python:3.11-slim

# Set the working directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Ensure the /data directory exists for the volume
RUN mkdir -p /data

# Copy the app code
COPY . .

# Expose the application port
EXPOSE 8000

# Run the app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Empty file added diffing/app/__init__.py
Empty file.
Empty file added diffing/app/auth/__init__.py
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from sqlalchemy.orm import Session
import jwt
from jwt import decode, PyJWTError
from diffing.models import Band, Token, TokenData
from diffing.database import get_db
from app.models import Band, Token, TokenData
from app.database import get_db
from typing import Optional
from fastapi.security import OAuth2PasswordBearer

Expand All @@ -17,7 +17,7 @@
# JWT Configuration
SECRET_KEY = "YTqyjx8ja5KiCl2vjgg9XCIujYAAAnjx" # Replace with a secure, unique key in production
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
ACCESS_TOKEN_EXPIRE_MINUTES = 300

# Helper function to create a JWT access token
def create_access_token(data: dict, expires_delta: timedelta = None):
Expand Down Expand Up @@ -65,8 +65,6 @@ async def get_current_band(token: str = Depends(oauth2_scheme), db: Session = De

# Query the database to retrieve the current band
band = db.query(Band).filter(Band.id == band_id).first()
print("alskjdflkjasdflkjasdflkjasdñlfkjalsdkfjaldkjsfadfkl")
print(band)
if band is None:
raise credentials_exception

Expand Down
26 changes: 26 additions & 0 deletions diffing/app/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
from pathlib import Path

# Determine the base directory of the project
BASE_DIR = Path(__file__).resolve().parent

# Directory for storing files (e.g., uploads or local database) in local development
UPLOAD_DIR = BASE_DIR / "files"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True) # Ensure the directory exists locally

# Set database URL based on the environment
if os.getenv("RAILWAY_ENVIRONMENT_NAME") == "production": # Check if running in production
# Use PostgreSQL DATABASE_URL for production
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
raise ValueError("DATABASE_URL is not set in the Railway environment.")
else:
# In local development, use SQLite
DATABASE_FILE = UPLOAD_DIR / "database.db"
DATABASE_URL = f"sqlite:///{DATABASE_FILE}"

# Construct the SQLAlchemy database URL
SQLALCHEMY_DATABASE_URL = DATABASE_URL

# Debugging: Print the resolved database URL
print(f"SQLAlchemy Database URL: {SQLALCHEMY_DATABASE_URL}")
10 changes: 5 additions & 5 deletions diffing/core.py → diffing/app/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ def find_changed_masterbars(old_master_bars: List[MasterBar], new_master_bars: L
max_length = max(len(old_master_bars), len(new_master_bars))

if DEBUG:
os.makedirs("tmp", exist_ok=True)
with open("tmp/old_master_bars.json", "w") as file:
os.makedirs("../tmp", exist_ok=True)
with open("../tmp/old_master_bars.json", "w") as file:
json.dump([asdict(master_bar) for master_bar in old_master_bars], file, indent=4)
with open("tmp/new_master_bars.json", "w") as file:
with open("../tmp/new_master_bars.json", "w") as file:
json.dump([asdict(master_bar) for master_bar in new_master_bars], file, indent=4)

for i in range(max_length):
Expand All @@ -137,9 +137,9 @@ def find_changed_masterbars(old_master_bars: List[MasterBar], new_master_bars: L
# This handles nested dataclasses automatically
if asdict(old_master) != asdict(new_master):
if DEBUG:
with open(f"tmp/old_{i}.json", "w") as file:
with open(f"../tmp/old_{i}.json", "w") as file:
json.dump(asdict(old_master), file, indent=4)
with open(f"tmp/new_{i}.json", "w") as file:
with open(f"../tmp/new_{i}.json", "w") as file:
json.dump(asdict(new_master), file, indent=4)

changed_indexes.add(i)
Expand Down
2 changes: 1 addition & 1 deletion diffing/crud.py → diffing/app/crud.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from sqlalchemy.orm import Session, joinedload
from diffing.models import SongMetadata, TabMetadata, Song, Tab
from app.models import SongMetadata, TabMetadata, Song, Tab
from typing import Optional

def create_song_with_tab(db: Session, title: str, filepath: str, band_id: int) -> SongMetadata:
Expand Down
47 changes: 47 additions & 0 deletions diffing/app/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.config import SQLALCHEMY_DATABASE_URL
import os

# Determine connection arguments based on the database type
connect_args = {"check_same_thread": False} if "sqlite" in SQLALCHEMY_DATABASE_URL else None

# SQLAlchemy engine configuration
if connect_args:
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args=connect_args # Pass this only if not None
)
else:
engine = create_engine(SQLALCHEMY_DATABASE_URL) # Omit connect_args entirely for PostgreSQL

# Session maker for database sessions
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Declarative base for ORM models
Base = declarative_base()

def initialize_database():
"""Initialize the database and create tables."""
if "sqlite" in SQLALCHEMY_DATABASE_URL:
# SQLite-specific logic
db_path = SQLALCHEMY_DATABASE_URL.replace("sqlite:///", "")
absolute_path = os.path.abspath(db_path)
print(f"Resolved database path: {absolute_path}")
print(f"Initializing database at: {db_path}")
if not os.path.exists(db_path):
print("Database file does not exist. Creating new database.")
else:
print("Database file already exists.")

# Create all tables using the engine
Base.metadata.create_all(bind=engine)

def get_db():
"""Provide a database session for dependency injection."""
db = SessionLocal()
try:
yield db
finally:
db.close()
32 changes: 24 additions & 8 deletions diffing/main.py → diffing/app/main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pathlib import Path

from diffing.auth import authentication
from diffing.config import UPLOAD_DIR
from diffing.database import initialize_database
from diffing.routers import bands, songs, comparison, setlists
from fastapi.responses import RedirectResponse

from app.auth import authentication
from app.config import UPLOAD_DIR
from app.database import initialize_database
from app.routers import bands, songs, comparison, setlists


app = FastAPI()
@asynccontextmanager
async def lifespan(app: FastAPI):
initialize_database()
yield

app = FastAPI(lifespan=lifespan)

# CORS Middleware Configuration
app.add_middleware(
Expand All @@ -23,12 +32,19 @@
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
app.mount("/static", StaticFiles(directory=UPLOAD_DIR), name="static")

# Initialize Database
initialize_database()
# # Startup Event to Initialize Database
# @app.on_event("startup")
# async def on_startup():
# initialize_database()

# Include Routers
app.include_router(songs.router)
app.include_router(comparison.router)
app.include_router(bands.router)
app.include_router(authentication.router)
app.include_router(setlists.router)


@app.get("/", include_in_schema=False)
async def root():
return RedirectResponse(url="/docs")
8 changes: 4 additions & 4 deletions diffing/models.py → diffing/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Enum, Text
from sqlalchemy.orm import relationship
from datetime import datetime
from diffing.database import Base
from app.database import Base
from typing import Optional
import enum
import uuid
Expand Down Expand Up @@ -44,7 +44,7 @@ class Song(SongBase):
tab: Optional["Tab"]

class Config:
orm_mode = True
from_attributes = True

class Tab(BaseModel):
id: int
Expand All @@ -53,7 +53,7 @@ class Tab(BaseModel):
uploaded_at: datetime

class Config:
orm_mode = True
from_attributes = True

class BandBase(BaseModel):
name: str
Expand All @@ -66,7 +66,7 @@ class BandSchema(BandBase):
access_code: str

class Config:
orm_mode = True
from_attributes = True

class Token(BaseModel):
access_token: str
Expand Down
Empty file added diffing/app/routers/__init__.py
Empty file.
8 changes: 4 additions & 4 deletions diffing/routers/bands.py → diffing/app/routers/bands.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from fastapi import APIRouter, Depends, HTTPException, status
from diffing.auth.authentication import get_current_band
from diffing.models import Band, BandCreate, BandSchema # Import necessary schemas
from app.auth.authentication import get_current_band
from app.models import Band, BandCreate, BandSchema # Import necessary schemas
from sqlalchemy.orm import Session
from diffing.database import get_db
from diffing.utils import generate_access_code
from app.database import get_db
from app.utils import generate_access_code

router = APIRouter(prefix="/bands", tags=["bands"])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
from sqlalchemy.orm import Session
from starlette.responses import JSONResponse

from diffing.core import compare_gpif_files
from diffing.database import get_db
from diffing.crud import get_tab_file_path
from diffing.utils import save_uploaded_file, extract_gpif
from app.core import compare_gpif_files
from app.database import get_db
from app.crud import get_tab_file_path
from app.utils import save_uploaded_file, extract_gpif
from pathlib import Path

router = APIRouter(prefix="/compare", tags=["comparison"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from sqlalchemy.orm import Session
from typing import List

from diffing.models import SetlistItem, SetlistItemCreate, SetlistItemSchema, SetlistItemType
from diffing.database import get_db
from app.models import SetlistItem, SetlistItemCreate, SetlistItemSchema, SetlistItemType
from app.database import get_db

router = APIRouter(prefix="/setlist_items", tags=["setlist_items"])

Expand Down
12 changes: 7 additions & 5 deletions diffing/routers/songs.py → diffing/app/routers/songs.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import os

from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Depends, status, Request, Body
from sqlalchemy.orm import Session
from typing import List
from diffing.database import get_db
from diffing.crud import create_song_with_tab, get_song_with_tab, get_all_songs
from diffing.models import Song, SongMetadata, Band
from diffing.utils import save_uploaded_file
from diffing.auth.authentication import get_current_band
from app.database import get_db
from app.crud import create_song_with_tab, get_song_with_tab, get_all_songs
from app.models import Song, SongMetadata, Band
from app.utils import save_uploaded_file
from app.auth.authentication import get_current_band
from pathlib import Path
from urllib.parse import urlparse

Expand Down
File renamed without changes.
Empty file added diffing/app/tests/__init__.py
Empty file.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pytest
from lxml import etree

from diffing.core import compare_gpif_files, materialize_gpif
from app.core import compare_gpif_files, materialize_gpif

__DIR__ = os.path.dirname(os.path.abspath(__file__))

Expand Down
File renamed without changes.
4 changes: 0 additions & 4 deletions diffing/config.py

This file was deleted.

18 changes: 0 additions & 18 deletions diffing/database.py

This file was deleted.

Binary file modified diffing/requirements.txt
Binary file not shown.
6 changes: 0 additions & 6 deletions package-lock.json

This file was deleted.

1 change: 0 additions & 1 deletion package.json

This file was deleted.

Loading

0 comments on commit 851c958

Please sign in to comment.