Skip to content

Commit

Permalink
Merge pull request #8 from Serg-Bartosh/chats
Browse files Browse the repository at this point in the history
add tests.py, fix bugs with photo and other
  • Loading branch information
Serg-Bartosh authored May 16, 2024
2 parents e546bd3 + 04753e6 commit 2e9a871
Show file tree
Hide file tree
Showing 92 changed files with 1,871 additions and 275 deletions.
2 changes: 1 addition & 1 deletion .idea/dataSources.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 10 additions & 11 deletions djangoProject1/asgi.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
"""
ASGI config for djangoProject1 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""

import os

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

from socialnetwork import urls

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject1.settings')
django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter({
"http": django_asgi_app,

application = get_asgi_application()
"websocket": AuthMiddlewareStack(URLRouter(urls.websocket_urlpatterns)),
})
23 changes: 22 additions & 1 deletion djangoProject1/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
ALLOWED_HOSTS = []

INSTALLED_APPS = [
"daphne",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
Expand All @@ -41,6 +42,8 @@
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',
'channels',
"payments",
]

MIDDLEWARE = [
Expand Down Expand Up @@ -79,7 +82,7 @@
},
]

WSGI_APPLICATION = 'djangoProject1.wsgi.application'
ASGI_APPLICATION = 'djangoProject1.asgi.application'

# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
Expand Down Expand Up @@ -136,3 +139,21 @@

MEDIA_ROOT = BASE_DIR / "media"
MEDIA_URL = '/media/'

CHANNEL_LAYERS = {
"default": {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}

PAYMENT_HOST = 'localhost:8000'

# Whether to use TLS (HTTPS). If false, will use plain-text HTTP.
# Defaults to ``not settings.DEBUG``.
PAYMENT_USES_SSL = False

PAYMENT_VARIANTS = {
'dummy': ('payments.dummy.DummyProvider', {})
}

PAYMENT_MODEL = 'socialnetwork.Payment'
16 changes: 0 additions & 16 deletions djangoProject1/wsgi.py

This file was deleted.

2 changes: 1 addition & 1 deletion qodana.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
#-------------------------------------------------------------------------------#
version: "1.0"

#Specify inspection profile for code analysis
#Specify inspection auth for code analysis
profile:
name: qodana.starter

Expand Down
1 change: 1 addition & 0 deletions socialnetwork/consumer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .сhat_сonsumer import ChatConsumer
68 changes: 68 additions & 0 deletions socialnetwork/consumer/сhat_сonsumer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
import json

from django.utils import timezone

from socialnetwork.models import Chat, ChatMessage


class ChatConsumer(JsonWebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = None
self.other_user_id = None
self.chat = None
self.room_name = None

def is_write_to_yourself(self):
if self.user == self.other_user_id:
self.close()

# TODO: проверка на то что бы юзер не писал сам себе
def create_room_name(self):
user_id = self.user.id
if user_id and self.other_user_id:
room_name = f'{min(user_id, self.other_user_id)}_{max(user_id, self.other_user_id)}'
self.room_name = room_name
else:
raise ValueError("Invalid user or user_id")

def connect(self):
self.user = self.scope["user"]
self.other_user_id = self.scope["url_route"]['kwargs']["user_id"]
self.is_write_to_yourself()
self.accept()
self.create_room_name()
self.chat, _ = Chat.objects.get_or_create(room_name=self.room_name)
async_to_sync(self.channel_layer.group_add)(
self.room_name,
self.channel_name,
)

def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.room_name,
self.channel_name,
)
self.close()

def receive(self, text_data):
data = json.loads(text_data)
message = data.get('message')
timestamp = timezone.now().isoformat()
if message:
message_obj = ChatMessage.objects.create(author=self.user, chat=self.chat, content=message)
async_to_sync(self.channel_layer.group_send)(
self.room_name,
{
'type': 'chat.message',
"author": self.user.username,
'content_id': message_obj.id,
'content': message,
'timestamp': timestamp
},
)

def chat_message(self, event):
self.send_json(event)
15 changes: 9 additions & 6 deletions socialnetwork/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from .user import *
from .article import *
from .avatar import *
from .photo import *
from .comment import *
from .like import *
from socialnetwork.models.profile.user import User
from socialnetwork.models.profile.avatar import Avatar
from socialnetwork.models.profile.photo import Photo
from socialnetwork.models.chat.chat import Chat
from socialnetwork.models.chat.message import ChatMessage
from socialnetwork.models.article.article import Article
from socialnetwork.models.article.like import ArticleLike
from socialnetwork.models.article.comment import CommentArticle
from socialnetwork.models.payment.payment import Payment
3 changes: 3 additions & 0 deletions socialnetwork/models/article/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from .article import *
# from .comment import *
# from .like import *
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import random

from django.core.validators import validate_image_file_extension
from django.db import models

from socialnetwork.models import User
Expand All @@ -15,7 +16,9 @@ class Article(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255, null=False, blank=False)
content = models.TextField(max_length=5000, null=False, blank=False)
image = models.ImageField(upload_to=file_location, null=False, blank=True)
image = models.ImageField(upload_to=file_location, null=False, blank=True,
max_length=1048576, # 1 Bite
validators=[validate_image_file_extension])
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created_at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="updated_at")

Expand Down
File renamed without changes.
File renamed without changes.
2 changes: 2 additions & 0 deletions socialnetwork/models/chat/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# from .chat import *
# from .message import *
9 changes: 9 additions & 0 deletions socialnetwork/models/chat/chat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.db import models


# TODO: Поменять способы сохранения сообщений:
# Добавить привязку юзеров к чату, создание груп

class Chat(models.Model):
room_name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created_at")
12 changes: 12 additions & 0 deletions socialnetwork/models/chat/message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from django.db import models
from rest_framework.authtoken.admin import User

from socialnetwork.models.chat.chat import Chat


class ChatMessage(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
content = models.CharField(max_length=256, blank=True)
state = models.CharField(default="NEW", max_length=10)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created_at")
1 change: 1 addition & 0 deletions socialnetwork/models/payment/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# from .payment import *
55 changes: 55 additions & 0 deletions socialnetwork/models/payment/payment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from decimal import Decimal
from typing import Iterable

from django.db.models.signals import pre_save
from django.dispatch import receiver
from payments import PurchasedItem
from payments.models import BasePayment

from djangoProject1.settings import PAYMENT_HOST
from django.db import models

from socialnetwork.models import User


class Payment(BasePayment):
user = models.ForeignKey(User, on_delete=models.PROTECT, default='')
price = models.DecimalField(max_digits=10000, decimal_places=2, default=0)
card_number = models.CharField(max_length=16, blank=True, null=True)
card_expiry_date = models.DateField(blank=True, null=True)
card_holder_name = models.CharField(max_length=255, blank=True, null=True)


@receiver(pre_save, sender=Payment)
def populate_payment_fields(sender, instance, **kwargs):
user = instance.user
if user:
instance.card_number = user.card_number
instance.card_expiry_date = user.card_expiry_date
instance.card_holder_name = user.card_holder_name


def get_failure_url(self) -> str:
print(self.price)
print('get_failure_url')

return f"http://{PAYMENT_HOST}/payments/{self.pk}/failure"


def get_success_url(self) -> str:
print(self.price)
print('get_success_url')

return f"http://{PAYMENT_HOST}/payments/{self.pk}/success"


def get_purchased_items(self) -> Iterable[PurchasedItem]:
print(self.price)
print('get_purchased_items')
yield PurchasedItem(
name='Donate for Ukrainian military',
sku='DFUM',
price=Decimal(self.price),
quantity=1,
currency=self.currency,
)
File renamed without changes.
3 changes: 3 additions & 0 deletions socialnetwork/models/profile/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from .avatar import *
# from .photo import *
# from .user import *
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.core.validators import validate_image_file_extension
from django.db import models
from django.utils.text import slugify

from djangoProject1.settings import MEDIA_ROOT
from socialnetwork.models import User


Expand All @@ -14,4 +14,6 @@ def file_location(instance, filename):

class Avatar(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to=file_location, null=False, blank=True)
image = models.ImageField(upload_to=file_location, null=False, blank=True,
max_length=1048576, # 1 Bite
validators=[validate_image_file_extension])
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.core.validators import validate_image_file_extension
from django.db import models

from socialnetwork.models import User
Expand All @@ -11,4 +12,5 @@ def file_location(instance, filename):

class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to=file_location, null=False, blank=True)
image = models.ImageField(upload_to=file_location, null=False, blank=True, max_length=1048576, # 1 Bite
validators=[validate_image_file_extension])
17 changes: 17 additions & 0 deletions socialnetwork/models/profile/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models

from socialnetwork.validator.user.card_number_validator import card_number_validator


class User(AbstractUser):
email = models.EmailField(max_length=255, unique=True, blank=False)
card_number = models.CharField(max_length=19, blank=True, null=True, unique=True,
validators=[card_number_validator])
card_expiry_date = models.DateField(blank=True, null=True)
card_holder_name = models.CharField(max_length=255, blank=True, null=True)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

objects = UserManager()
11 changes: 0 additions & 11 deletions socialnetwork/models/user.py

This file was deleted.

2 changes: 1 addition & 1 deletion socialnetwork/serializers/article/comment.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from rest_framework import serializers
from socialnetwork.models.comment import CommentArticle
from socialnetwork.models.article.comment import CommentArticle


class CommentArticleSerializer(serializers.ModelSerializer):
Expand Down
4 changes: 3 additions & 1 deletion socialnetwork/serializers/article/like.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from rest_framework import serializers
from socialnetwork.models.like import ArticleLike
from socialnetwork.models.article.like import ArticleLike


class LikeArticleSerializer(serializers.ModelSerializer):
like = serializers.BooleanField(required=True)

class Meta:
model = ArticleLike
fields = ['like']
Loading

0 comments on commit 2e9a871

Please sign in to comment.