Skip to content

Commit

Permalink
Merge pull request #59 from Fntoomen/devel
Browse files Browse the repository at this point in the history
Lint and cleanup
  • Loading branch information
mikolajlubiak authored Aug 13, 2023
2 parents a2d45cc + 31b8a2f commit 5aa1033
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 49 deletions.
4 changes: 2 additions & 2 deletions .env.dist
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ MYSQL_PORT=3307
HTTP_HOST=0.0.0.0
HTTP_PORT=8080

#OAUTH
# OAUTH
REDIRECT_URL=REDIRECT_URL
CLIENT_SECRET=USER_SECRET
CLIENT_ID=CLIENT_ID
AUTH_START_URL=AUTH_START_URL

#BOT
# BOT
BOT_TOKEN=BOT_TOKEN
2 changes: 1 addition & 1 deletion foreign_key_checks.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ set -o allexport
source .env
set +o allexport

docker exec -i motey_db_1 sh -c "exec mariadb -uroot -p$MYSQL_ROOT_PASSWORD -e 'SET GLOBAL FOREIGN_KEY_CHECKS = 0;'"
docker exec -i motey-db-1 sh -c "exec mariadb -uroot -p$MYSQL_ROOT_PASSWORD -e 'SET GLOBAL FOREIGN_KEY_CHECKS = 0;'"
4 changes: 2 additions & 2 deletions motey/infrastructure/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ class Config:
static_files_dir = project_root / 'static'
emotes_dir = project_root / 'static' / 'emotes'

#OAUTH
# OAUTH
client_secret = os.getenv('CLIENT_SECRET')
client_id = os.getenv('CLIENT_ID')
redirect_url = os.getenv('REDIRECT_URL')
auth_start_url = os.getenv('AUTH_START_URL')

#BOT
# BOT
token = os.getenv('BOT_TOKEN')
1 change: 1 addition & 0 deletions motey/infrastructure/database/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@

from motey.infrastructure.database.dsn import build_dsn


def get_db() -> Engine:
return create_engine(build_dsn())
2 changes: 2 additions & 0 deletions motey/infrastructure/database/init_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
from motey.infrastructure.database.engine import get_db
from motey.infrastructure.database.tables import Base


def init_db(engine: sqlalchemy.Engine = get_db()) -> None:
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)


if __name__ == '__main__':
init_db()
2 changes: 1 addition & 1 deletion motey/infrastructure/database/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from sqlalchemy import select, exists
from sqlalchemy.orm import Session
from sqlalchemy import func

from motey.infrastructure.database.tables import Emote, Server, User

Expand Down Expand Up @@ -37,6 +36,7 @@ def get_emote_by_name(self, name: str) -> Optional[Emote]:
except:
return None


class UserStorage:
def __init__(self, database):
self._db = database
Expand Down
55 changes: 29 additions & 26 deletions motey/infrastructure/database/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
)
from typing import List, Optional


class Base(DeclarativeBase):
pass
pass


users_servers_association_table = Table(
"users_servers_association_table",
Expand All @@ -38,34 +40,35 @@ class Base(DeclarativeBase):
Column("server_id", ForeignKey("servers.id"), primary_key=True),
Column("emote_id", ForeignKey("emotes.id"), primary_key=True),
)



class Server(Base):
__tablename__ = "servers"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(32), nullable=False)
guild: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True)
server_users: Mapped[List["User"]] = relationship(back_populates="user_servers", secondary=users_servers_association_table)
server_admins: Mapped[List["User"]] = relationship(back_populates="admin_servers", secondary=admins_servers_association_table)
server_emotes: Mapped[List["Emote"]] = relationship(back_populates="emote_servers", secondary=emotes_servers_association_table)
__tablename__ = "servers"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(32), nullable=False)
guild: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True)
server_users: Mapped[List["User"]] = relationship(back_populates="user_servers", secondary=users_servers_association_table)
server_admins: Mapped[List["User"]] = relationship(back_populates="admin_servers", secondary=admins_servers_association_table)
server_emotes: Mapped[List["Emote"]] = relationship(back_populates="emote_servers", secondary=emotes_servers_association_table)


class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(32), nullable=False, unique=True)
discord_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True)
user_servers: Mapped[Optional[List["Server"]]] = relationship(back_populates="server_users", secondary=users_servers_association_table)
admin_servers: Mapped[Optional[List["Server"]]] = relationship(back_populates="server_admins", secondary=admins_servers_association_table)
user_emotes: Mapped[Optional[List["Emote"]]] = relationship(back_populates="author")
replace: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
banned: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(32), nullable=False, unique=True)
discord_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True)
user_servers: Mapped[Optional[List["Server"]]] = relationship(back_populates="server_users", secondary=users_servers_association_table)
admin_servers: Mapped[Optional[List["Server"]]] = relationship(back_populates="server_admins", secondary=admins_servers_association_table)
user_emotes: Mapped[Optional[List["Emote"]]] = relationship(back_populates="author")
replace: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
banned: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)


class Emote(Base):
__tablename__ = "emotes"

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
author_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
author: Mapped["User"] = relationship(back_populates="user_emotes")
emote_servers: Mapped[Optional[List["Server"]]] = relationship(back_populates="server_emotes", secondary=emotes_servers_association_table)
name: Mapped[str] = mapped_column(String(32), nullable=False)
path: Mapped[str] = mapped_column(String(128), nullable=False, unique=True)
__tablename__ = "emotes"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
author_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
author: Mapped["User"] = relationship(back_populates="user_emotes")
emote_servers: Mapped[Optional[List["Server"]]] = relationship(back_populates="server_emotes", secondary=emotes_servers_association_table)
name: Mapped[str] = mapped_column(String(32), nullable=False)
path: Mapped[str] = mapped_column(String(128), nullable=False, unique=True)
21 changes: 13 additions & 8 deletions motey/infrastructure/discord/bot.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import nextcord

from sqlalchemy import insert, select, update, exists
from sqlalchemy import select, update, exists
from sqlalchemy.orm import Session

from motey.infrastructure.database.storage import EmoteStorage
from motey.infrastructure.database.tables import User, Server, Emote
from motey.infrastructure.database.tables import User
from motey.infrastructure.database.engine import get_db
from motey.infrastructure.config import Config


class MoteyClient(nextcord.Client):
def __init__(self, emote_storage: EmoteStorage = EmoteStorage(get_db())):
intents = nextcord.Intents.default()
Expand All @@ -27,9 +28,9 @@ async def on_message(self, message):
db_session.add(user)
db_session.commit()
with Session(get_db()) as db_session:
stmt = select(User).where(User.discord_id==message.author.id)
stmt = select(User).where(User.discord_id == message.author.id)
author = db_session.scalars(stmt).one()
if author.replace==False:
if author.replace is False:
return
emote = self._emotes.get_emote_by_name(message.content)
if emote is not None:
Expand All @@ -40,7 +41,10 @@ async def on_message(self, message):
await webhook.send(file=picture, username=message.author.name, avatar_url=message.author.avatar)
await webhook.delete()


client = MoteyClient()


@client.slash_command()
async def toggle_replacing(interaction: nextcord.Interaction):
with Session(get_db()) as db_session:
Expand All @@ -49,13 +53,14 @@ async def toggle_replacing(interaction: nextcord.Interaction):
db_session.add(user)
db_session.commit()
with Session(get_db()) as db_session:
stmt = select(User).where(User.discord_id==interaction.user.id)
stmt = select(User).where(User.discord_id == interaction.user.id)
author = db_session.scalars(stmt).one()
with Session(get_db()) as db_session:
stmt = (
update(User)
.where(User.discord_id == interaction.user.id)
.values(replace=not author.replace))
update(User)
.where(User.discord_id == interaction.user.id)
.values(replace=not author.replace)
)
author.replace = not author.replace
db_session.execute(stmt)
db_session.commit()
Expand Down
1 change: 1 addition & 0 deletions motey/infrastructure/http/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ async def handle_404(request):
async def handle_500(request):
return aiohttp_jinja2.render_template('500.html', request, {}, status=500)


@web.middleware
async def check_login(request, handler):
if request.path == '/upload':
Expand Down
4 changes: 2 additions & 2 deletions motey/infrastructure/http/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from motey.infrastructure.config import Config

from motey.infrastructure.http.views import list_emotes, index, process_oauth, process_upload, upload
from motey.infrastructure.config import Config


def setup_routes(app: Application, config: Config = Config()) -> None:
app.router.add_static(str(config.emotes_dir), config.emotes_dir)
Expand All @@ -13,4 +13,4 @@ def setup_routes(app: Application, config: Config = Config()) -> None:
app.router.add_get('/upload', upload)
app.router.add_get('/process_oauth', process_oauth)
app.router.add_static('/static/', path=(config.static_files_dir), name='static')
app.router.add_get('/login', lambda _: web.HTTPFound(location=config.auth_start_url))
app.router.add_get('/login', lambda _: web.HTTPFound(location=config.auth_start_url))
15 changes: 8 additions & 7 deletions motey/infrastructure/http/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
import aiohttp_jinja2
import aiohttp_session

from sqlalchemy import insert, select, update, exists
from sqlalchemy import select, exists
from sqlalchemy.orm import Session

from motey.infrastructure.database.storage import EmoteStorage, UserStorage
from motey.infrastructure.database.storage import EmoteStorage
from motey.infrastructure.filesystem import EmoteFileWriter
from motey.infrastructure.database.tables import User, Server, Emote, users_servers_association_table
from motey.infrastructure.database.tables import User, Server

from motey.infrastructure.config import Config

routes = web.RouteTableDef()


@aiohttp_jinja2.template('list.html')
async def list_emotes(request: web.Request):
emotes_list = EmoteStorage(request.app['db']).fetch_all_emotes()
Expand Down Expand Up @@ -45,10 +46,10 @@ async def process_upload(request: web.Request):
return {'error_message': 'Emote file or emote name empty'}

with Session(request.app['db']) as db_session:
stmt = select(User).where(User.discord_id==session['discord_id'])
stmt = select(User).where(User.discord_id == session['discord_id'])
author = db_session.scalars(stmt).one()

if author.banned==True:
if author.banned is True:
return {'error_message': 'User banned from uploading emotes'}

file_writer = EmoteFileWriter(emote_name, emote.filename, emote.file)
Expand Down Expand Up @@ -86,7 +87,7 @@ async def process_oauth(request: web.Request):
header = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/x-www-form-urlencoded"
}
}
async with aiohttp.ClientSession(headers=header) as client_session:
async with client_session.get("https://discord.com/api/users/@me") as response:
user_data = await response.json()
Expand All @@ -102,7 +103,7 @@ async def process_oauth(request: web.Request):
stmt = select(User).where(User.discord_id == session['discord_id'])
user = db_session.scalars(stmt)
for guild in guilds:
#add name updating in existing guilds
# add name updating in existing guilds
guild_id = int(guild["id"])
guild_name = guild["name"]
if not db_session.query(exists().where(Server.guild == guild_id)).scalar():
Expand Down

0 comments on commit 5aa1033

Please sign in to comment.