Skip to content
This repository was archived by the owner on Apr 29, 2025. It is now read-only.

Commit 2709744

Browse files
authored
Merge pull request #24 from nickatnight/nickatnight-GH-23
[GH-23] New is_it field and update logic
2 parents 85cdd60 + 01cccca commit 2709744

File tree

17 files changed

+101
-105
lines changed

17 files changed

+101
-105
lines changed

.github/workflows/build.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ jobs:
2525
token: ${{ secrets.do-token }}
2626
- name: Build backend
2727
run: |
28-
docker build --build-arg env=staging -t ${{ secrets.registry }}/backend:${{ github.sha }} ./backend
28+
docker build --build-arg env=prod -t ${{ secrets.registry }}/backend:${{ github.sha }} ./backend
2929
- name: Log in to DigitalOcean Container Registry with short-lived credentials
3030
run: doctl registry login --expiry-seconds 600
3131
- name: Push image to DigitalOcean Container Registry
@@ -43,7 +43,7 @@ jobs:
4343
token: ${{ secrets.do-token }}
4444
- name: Build nginx
4545
run: |
46-
docker build --build-arg env=staging -t ${{ secrets.registry }}/nginx:${{ github.sha }} ./nginx
46+
docker build --build-arg env=prod -t ${{ secrets.registry }}/nginx:${{ github.sha }} ./nginx
4747
- name: Log in to DigitalOcean Container Registry with short-lived credentials
4848
run: doctl registry login --expiry-seconds 600
4949
- name: Push image to DigitalOcean Container Registry

.github/workflows/main.yml

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ on:
66
- '*'
77
branches:
88
- main
9-
- develop
109

1110
env:
1211
DOCTL_VERSION: 1.92.0
@@ -42,47 +41,48 @@ jobs:
4241
- name: Checkout
4342
uses: actions/checkout@v3
4443

45-
- name: Deploy staging
44+
# - name: Deploy staging
45+
# uses: ironhalik/docker-over-ssh-action@v6
46+
# if: github.ref == 'refs/heads/develop'
47+
# env:
48+
# COMPOSE_FILE: ops/docker-compose.staging.yml
49+
# STACK_NAME: tagyoureitbackend-staging
50+
# DIGITALOCEAN_ACCESS_TOKEN: ${{ secrets.DIGITALOCEAN_TOKEN }}
51+
# REGISTRY: ${{ secrets.REGISTRY }}
52+
# POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
53+
# POSTGRES_STAGING_HOST: ${{ secrets.POSTGRES_STAGING_HOST }}
54+
# PASSWORD: ${{ secrets.PASSWORD }}
55+
# CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
56+
# with:
57+
# user: ubuntu
58+
# host: ${{ secrets.STAGING_HOST_IP }}
59+
# key: ${{ secrets.SSH_KEY }}
60+
# script: |
61+
# wget https://github.com/digitalocean/doctl/releases/download/v${{ env.DOCTL_VERSION }}/doctl-${{ env.DOCTL_VERSION }}-linux-amd64.tar.gz
62+
# tar xf ./doctl-${{ env.DOCTL_VERSION }}-linux-amd64.tar.gz
63+
# mv ./doctl /usr/local/bin
64+
# doctl registry login
65+
# docker stack deploy --compose-file ${COMPOSE_FILE} --with-registry-auth --prune ${STACK_NAME}
66+
67+
- name: Deploy prod
4668
uses: ironhalik/docker-over-ssh-action@v6
47-
if: github.ref == 'refs/heads/develop'
69+
if: github.ref == 'refs/heads/main'
4870
env:
49-
COMPOSE_FILE: ops/docker-compose.staging.yml
50-
STACK_NAME: tagyoureitbackend-staging
71+
COMPOSE_FILE: ops/docker-compose.prod.yml
72+
STACK_NAME: tagyoureitbackend-prod
5173
DIGITALOCEAN_ACCESS_TOKEN: ${{ secrets.DIGITALOCEAN_TOKEN }}
5274
REGISTRY: ${{ secrets.REGISTRY }}
5375
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
54-
POSTGRES_STAGING_HOST: ${{ secrets.POSTGRES_STAGING_HOST }}
76+
POSTGRES_PROD_HOST: ${{ secrets.POSTGRES_PROD_HOST }}
5577
PASSWORD: ${{ secrets.PASSWORD }}
5678
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
5779
with:
5880
user: ubuntu
59-
host: ${{ secrets.STAGING_HOST_IP }}
81+
host: ${{ secrets.PROD_HOST_IP }}
6082
key: ${{ secrets.SSH_KEY }}
6183
script: |
6284
wget https://github.com/digitalocean/doctl/releases/download/v${{ env.DOCTL_VERSION }}/doctl-${{ env.DOCTL_VERSION }}-linux-amd64.tar.gz
6385
tar xf ./doctl-${{ env.DOCTL_VERSION }}-linux-amd64.tar.gz
6486
mv ./doctl /usr/local/bin
6587
doctl registry login
6688
docker stack deploy --compose-file ${COMPOSE_FILE} --with-registry-auth --prune ${STACK_NAME}
67-
68-
# - name: Deploy prod
69-
# uses: ironhalik/docker-over-ssh-action@v6
70-
# if: github.ref == 'refs/heads/main'
71-
# env:
72-
# COMPOSE_FILE: ops/docker-compose.prod.yml
73-
# STACK_NAME: tagyoureitbackend-prod
74-
# DIGITALOCEAN_ACCESS_TOKEN: ${{ secrets.DIGITALOCEAN_TOKEN }}
75-
# REGISTRY: ${{ secrets.REGISTRY }}
76-
# POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
77-
# PASSWORD: ${{ secrets.PASSWORD }}
78-
# CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
79-
# with:
80-
# user: ubuntu
81-
# host: ${{ secrets.PROD_HOST_IP }}
82-
# key: ${{ secrets.SSH_KEY }}
83-
# script: |
84-
# wget https://github.com/digitalocean/doctl/releases/download/v${{ env.DOCTL_VERSION }}/doctl-${{ env.DOCTL_VERSION }}-linux-amd64.tar.gz
85-
# tar xf ./doctl-${{ env.DOCTL_VERSION }}-linux-amd64.tar.gz
86-
# mv ./doctl /usr/local/bin
87-
# doctl registry login
88-
# docker stack deploy --compose-file ${COMPOSE_FILE} --with-registry-auth --prune ${STACK_NAME}

.github/workflows/pr.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ on:
66
pull_request:
77
branches:
88
- main
9-
- develop
109

1110
jobs:
1211
lint:

backend/src/core/const.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,17 +68,14 @@ class Envs:
6868
else ""
6969
)
7070

71-
SUB_DOMAIN = "api"
72-
if settings.ENV != Envs.PRODUCTION:
73-
SUB_DOMAIN = "api-staging"
7471

7572
FOOTER = (
7673
"^^[ how to use]"
7774
"(https://www.reddit.com/r/TagYoureItBot/comments/11bcwi1/tagyoureitbot_info_beta_relase/)"
7875
" | [creator](https://www.reddit.com/message/compose/?to=throwie_one)"
7976
" | [source code](https://github.com/nickatnight/tag-youre-it-backend)"
8077
" | [wikihow](https://www.wikihow.com/Play-Tag)"
81-
f" | [public api](https://{SUB_DOMAIN}.tagyoureitbot.com/docs)"
78+
f" | [public api](https://api.tagyoureitbot.com/docs)"
8279
" | [website](https://tagyoureitbot.com)"
8380
f"{OPT_OUT}"
8481
)

backend/src/core/decorators.py

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,24 @@
1-
# import logging
2-
# from typing import Any, Callable
1+
import functools
2+
import logging
3+
from typing import Any
34

4-
# import asyncprawcore
5-
# from result import Result, Ok, Err
5+
import asyncprawcore
66

77

8-
# logger = logging.getLogger(__name__)
8+
logger = logging.getLogger(__name__)
99

1010

11-
# class CatchAsyncPraw:
12-
# """generic catch handler for methods using asyncpraw"""
13-
# def __init__(self, function: Callable[..., Any]) -> None:
14-
# self.function = function
11+
def catch_apraw_and_log(func):
12+
@functools.wraps(func)
13+
async def wrapper_catch_apraw_and_log(*args, **kwargs):
14+
try:
15+
result: Any = await func(*args, **kwargs)
16+
except asyncprawcore.exceptions.RequestException as a_exc:
17+
logger.warning(a_exc, exc_info=True)
18+
except Exception as e:
19+
logger.warning(e, exc_info=True)
20+
else:
21+
return result
22+
return False
1523

16-
# def __call__(self, *args: str, **kwargs: Any) -> Result[Any, str]:
17-
# try:
18-
# result: Any = self.function(*args, **kwargs)
19-
# except asyncprawcore.exceptions.RequestException as a_exc:
20-
# logger.error(a_exc, exc_info=True)
21-
# return Err(str(a_exc))
22-
# except Exception as e:
23-
# logger.error(e, exc_info=True)
24-
# return Err(f"Unknown error occurred: {e}")
25-
# else:
26-
# return Ok(result)
24+
return wrapper_catch_apraw_and_log

backend/src/migrations/versions/001ed18e8a99_init.py renamed to backend/src/migrations/versions/dcf44004a9e6_init.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
"""init
22
3-
Revision ID: 001ed18e8a99
3+
Revision ID: dcf44004a9e6
44
Revises:
5-
Create Date: 2023-02-24 02:29:14.014323
5+
Create Date: 2023-03-09 21:53:18.928636
66
77
"""
88
from alembic import op
@@ -11,7 +11,7 @@
1111

1212

1313
# revision identifiers, used by Alembic.
14-
revision = '001ed18e8a99'
14+
revision = 'dcf44004a9e6'
1515
down_revision = None
1616
branch_labels = None
1717
depends_on = None
@@ -33,6 +33,7 @@ def upgrade() -> None:
3333
sa.Column('is_suspended', sa.Boolean(), nullable=True),
3434
sa.Column('opted_out', sa.Boolean(), nullable=True),
3535
sa.Column('is_banned', sa.Boolean(), nullable=True),
36+
sa.Column('is_it', sa.Boolean(), nullable=True),
3637
sa.Column('ref_id', sqlmodel.sql.sqltypes.GUID(), server_default=sa.text('gen_random_uuid()'), nullable=False),
3738
sa.Column('id', sa.Integer(), nullable=False),
3839
sa.PrimaryKeyConstraint('id'),

backend/src/models/player.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ class PlayerBase(SQLModel):
3838
# game fields
3939
opted_out: Optional[bool] = Field(default=False, description="Did the user opt out of playing.")
4040
is_banned: Optional[bool] = Field(default=False, description="Is the user banned from playing.")
41+
is_it: Optional[bool] = Field(default=False, description="Is the user it.")
4142
tag_time: Optional[datetime] = Field(
4243
sa_column=Column(
4344
DateTime(timezone=True),

backend/src/repositories/sqlalchemy.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ async def create(self, obj_in: CreateSchemaType, **kwargs: Any) -> ModelType:
4646
return db_obj
4747

4848
async def get(self, **kwargs: Any) -> Optional[ModelType]:
49-
logger.info(f"Fetching [{self._model.__class__.__name__}] object by [{kwargs}]")
49+
logger.info(f"Fetching [{self._model.__table__.name.capitalize()}] object by [{kwargs}]")
5050

5151
query = select(self._model).filter_by(**kwargs)
5252
response = await self.db.execute(query)
@@ -58,7 +58,7 @@ async def get(self, **kwargs: Any) -> Optional[ModelType]:
5858
return scalar
5959

6060
async def update(self, obj_current: ModelType, obj_in: UpdateSchemaType) -> ModelType:
61-
logger.info(f"Updating [{self._model.__class__.__name__}] object with [{obj_in}]")
61+
logger.info(f"Updating [{self._model.__table__.name.capitalize()}] object with [{obj_in}]")
6262

6363
update_data = obj_in.dict(
6464
exclude_unset=True
@@ -101,7 +101,7 @@ async def all(
101101
return response.scalars().all()
102102

103103
async def f(self, **kwargs: Any) -> List[ModelType]:
104-
logger.info(f"Fetching [{self._model.__class__.__name__}] object by [{kwargs}]")
104+
logger.info(f"Filtering [{self._model.__table__.name.capitalize()}] object by [{kwargs}]")
105105

106106
query = select(self._model).filter_by(**kwargs)
107107
response = await self.db.execute(query)

backend/src/services/game.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import logging
2-
from typing import List, Optional, Union
2+
from typing import Optional, Union
33
from uuid import UUID
44

55
from sqlmodel import select
@@ -41,14 +41,18 @@ async def add_player(self, player: Player, game_ref_id: Union[UUID, str]) -> Non
4141

4242
logger.info(f"Adding Players[{player.username}] to Game[{game.ref_id}]")
4343

44-
async def active(self) -> List[Game]:
44+
async def active(self, sub: SubReddit) -> Optional[Game]:
4545
logger.info("Fetching current game")
4646
statement = (
4747
select(self.repo._model)
4848
.where(self.repo._model.is_active == True) # noqa
49+
.where(self.repo._model.subreddit_id == sub.id)
4950
.order_by(self.repo._model.__table__.columns["created_at"].desc()) # type: ignore
5051
)
5152
results = await self.repo.db.execute(statement)
52-
games: List[Game] = results.scalars().all()
53+
game: Optional[Game] = results.scalar_one_or_none()
5354

54-
return games
55+
if not game:
56+
logger.info(f"No Game found for sub[{sub.ref_id}]")
57+
58+
return game

backend/src/services/player.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ async def set_opted_out(self, reddit_id: str, value: bool) -> None:
2828
if not player:
2929
raise ObjectNotFound
3030

31-
player_obj = IPlayerUpdate(opted_out=value)
31+
player_obj = IPlayerUpdate(opted_out=value, is_it=False)
3232
_ = await self.repo.update(player, player_obj)
3333

3434
logger.info(f"[{player.username}] opted out of playing.")
@@ -51,11 +51,11 @@ async def get_or_create(self, reddit_obj: Redditor) -> Player:
5151
async def untag(self, reddit_obj: Redditor) -> None:
5252
instance = await self.get_or_create(reddit_obj)
5353

54-
player_obj = IPlayerUpdate(tag_time=None)
54+
player_obj = IPlayerUpdate(is_it=False)
5555
_ = await self.repo.update(instance, player_obj)
5656

5757
async def tag(self, reddit_obj: Redditor) -> None:
5858
instance = await self.get_or_create(reddit_obj)
5959

60-
player_obj = IPlayerUpdate(tag_time=datetime.now(timezone.utc))
60+
player_obj = IPlayerUpdate(tag_time=datetime.now(timezone.utc), is_it=True)
6161
_ = await self.repo.update(instance, player_obj)

0 commit comments

Comments
 (0)