Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# =========================
# Sphinx documentation
# =========================
docs/_build/

# =========================
# Python / general
# =========================
Expand Down
6 changes: 5 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ FROM python:3.11-slim

WORKDIR /app

RUN apt-get update \
&& apt-get install -y --no-install-recommends graphviz \
&& rm -rf /var/lib/apt/lists/*

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "Fools_Arena.asgi:application", "--bind", "0.0.0.0:8000"]
CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "Fools_Arena.asgi:application"]
12 changes: 7 additions & 5 deletions Fools_Arena/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,17 @@

import os

import django
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter

from Fools_Arena.routing import websocket_application


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Fools_Arena.settings")
django.setup()

from Fools_Arena.routing import websocket_application

application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": websocket_application,
})
"websocket": AuthMiddlewareStack(websocket_application),
})
6 changes: 2 additions & 4 deletions Fools_Arena/routing.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
from channels.routing import URLRouter
from channels.auth import AuthMiddlewareStack

from chat.routing import websocket_urlpatterns as chat_routes
from game.routing import websocket_urlpatterns as game_routes

websocket_application = AuthMiddlewareStack(
URLRouter(chat_routes + game_routes)
)
# AuthMiddlewareStack is applied once in asgi.py (do not wrap here too).
websocket_application = URLRouter(chat_routes + game_routes)
20 changes: 18 additions & 2 deletions Fools_Arena/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_extensions",
'rest_framework',
'accounts',
'chat',
Expand All @@ -52,10 +53,14 @@

CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer"
}
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("redis", 6379)],
},
},
}


MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
Expand Down Expand Up @@ -121,6 +126,8 @@

AUTH_USER_MODEL = 'accounts.User'

LOGIN_URL = "/accounts/login/"

# Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/

Expand All @@ -143,3 +150,12 @@
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
}
13 changes: 13 additions & 0 deletions Fools_Arena/test_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""Django settings for automated tests (no Redis dependency).

Extends production settings but swaps the Channels layer for an in-memory
backend so ``pytest`` does not require a running Redis instance.
"""

from Fools_Arena.settings import * # noqa: F401,F403 pylint:disable=wildcard-import,unused-wildcard-import

CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
},
}
13 changes: 7 additions & 6 deletions Fools_Arena/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,15 @@

urlpatterns = [
path("admin/", admin.site.urls),
# UI
path('accounts/', include('accounts.urls')),

# UI
path("accounts/", include("accounts.urls")),
path("chat/", include("chat.urls")),
path("game/", include("game.urls")),
# API
path('api/accounts/', include('accounts.api_urls')),

path("api/accounts/", include("accounts.api_urls")),
path("api/chat/", include("chat.api_urls")),
path("api/game/", include("game.api_urls")),
]

# Add static files
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

76 changes: 72 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,89 @@ docker compose exec web python manage.py collectstatic
```

### 6. Work with Django
All commands should be executed inside the web container. Examples:
Run migrations, tests, and management commands **inside the `web` container** (after `docker compose up`):

```bash
docker compose exec web python manage.py shell
docker compose exec web python manage.py migrate
docker compose exec web python manage.py makemigrations
docker compose exec web pytest -v
docker compose exec web pytest -v
```

If containers are not running yet, you can use a one-off container (starts dependencies per Compose file):

```bash
docker compose run --rm web python manage.py migrate
docker compose run --rm web pytest -v
```

### Chat: API and templates
REST (session or token auth as configured for DRF):

- `GET /api/chat/chats/` — list chats for the current user
- `POST /api/chat/chats/direct/` — JSON body `{ "other_user_id": "<uuid>" }` to open or reuse a 1:1 chat
- `GET|POST /api/chat/chats/<chat_uuid>/messages/` — list recent messages or `{ "content": "..." }` to post

Same behaviour in server-rendered UI (login required):

- `/chat/` — inbox
- `/chat/direct/new/` — start a direct chat by username
- `/chat/<chat_uuid>/` — history, HTTP post form, optional WebSocket client block on the page

Blocking uses `accounts.Block`: the blocked user cannot send **direct** messages to the blocker; lobby chats are unchanged.

### 7. Stop containers
```bash
docker compose down
```
---

## Documentation

Developer documentation is built with [Sphinx](https://www.sphinx-doc.org/) from the [`docs/`](docs/) directory (autodoc, Google-style docstrings via Napoleon, viewcode).

**Install dependencies** (includes Sphinx):

```bash
pip install -r requirements.txt
```

**Generate HTML** (either command from the repository root):

```bash
cd docs && make html
```

```bash
sphinx-build -b html docs docs/_build
```

Open `docs/_build/html/index.html` in a browser.

**Rebuild after code or docstring changes** (clean output, then build again):

```bash
cd docs && make clean html
```

Or remove the build directory and run `sphinx-build` again:

```bash
rm -rf docs/_build && sphinx-build -b html docs docs/_build
```

**Using Docker** (from the project root, with the stack running and the app image built):

```bash
docker compose exec web sphinx-build -b html docs docs/_build
```

The `docs/_build/` directory is gitignored.

---

## 🚀 Stack
- Django, REST, Channels
- Django, REST, Channels
- Redis
- PostgreSQL
- Docker
- GitFlow
Expand Down
28 changes: 28 additions & 0 deletions accounts/migrations/0003_block.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 5.2.6 on 2025-11-14 19:37

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('accounts', '0002_alter_user_options'),
]

operations = [
migrations.CreateModel(
name='Block',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('blocked', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blocks_received', to=settings.AUTH_USER_MODEL)),
('blocker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blocks_initiated', to=settings.AUTH_USER_MODEL)),
],
options={
'indexes': [models.Index(fields=['blocker', 'blocked'], name='accounts_bl_blocker_746a2a_idx')],
'unique_together': {('blocker', 'blocked')},
},
),
]
Loading
Loading