Skip to content

Commit

Permalink
related with #71
Browse files Browse the repository at this point in the history
  • Loading branch information
punkyoon committed Mar 2, 2017
1 parent 02cf309 commit fae839d
Show file tree
Hide file tree
Showing 17 changed files with 52 additions and 93 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ install:
script:
- "python secret_key_gen.py"
- "python manage.py migrate"
- "flake8 --count --exclude ./docs,./manage_room/diff_match_patch,./manage_room/migrations,./manage_chat/migrations"
- "flake8 --count --ignore=E501,E302,W293,F841 --exclude ./docs,./manage_room/diff_match_patch,./manage_room/migrations,./manage_chat/migrations,./manage.py"
5 changes: 3 additions & 2 deletions coding_night_live/consumers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json

from channels import Channel, Group
from channels import Channel
from channels.auth import channel_session_user_from_http, channel_session_user

from manage_room.models import Room
Expand All @@ -11,11 +11,13 @@ def ws_connect(message):
message.reply_channel.send({'accept': True})
message.channel_session['room'] = []


def ws_receive(message):
payload = json.loads(message['text'])
payload['reply_channel'] = message.content['reply_channel']
Channel('room.receive').send(payload)


@channel_session_user
def ws_disconnect(message):
for room_label in message.channel_session.get("room", set()):
Expand All @@ -24,4 +26,3 @@ def ws_disconnect(message):
room.websocket_group.discard(message.reply_channel)
except Room.DoesNotExist:
pass

10 changes: 0 additions & 10 deletions coding_night_live/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,7 @@
channel_routing = [
# /Room/
include("coding_night_live.routing.websocket_routing", path=r"^/room/"),
#include("manage_room.routing.websocket_routing", path=r"^/room/user_count/"),
include("manage_room.routing.custom_routing"),
# /Chat/
#include("manage_chat.routing.websocket_routing", path=r"^/talk/"),
include("manage_chat.routing.custom_routing"),
]

"""
websocket_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", ws_receive),
route("websocket.disconnect", ws_disconnect),
]
"""
15 changes: 9 additions & 6 deletions coding_night_live/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@
with open(secret_file, 'r') as f:
secret = json.loads(f.read())


def get_secret(setting, secret=secret):
try:
return secret[setting]
except KeyError:
error_msg = "Set the {0} environment variable".format(setting)
raise ImproperlyConfigured(error_msg)


SECRET_KEY = get_secret('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
Expand Down Expand Up @@ -81,7 +83,7 @@ def get_secret(setting, secret=secret):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),], # templates DIR
'DIRS': [os.path.join(BASE_DIR, 'templates'), ], # templates DIR
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand All @@ -103,9 +105,9 @@ def get_secret(setting, secret=secret):

# django social auth setting
SOCIALACCOUNT_PROVIDERS = \
{ 'google':
{ 'SCOPE': ['profile', 'email'],
'AUTH_PARAMS': { 'access_type': 'online' } }}
{'google':
{'SCOPE': ['profile', 'email'],
'AUTH_PARAMS': {'access_type': 'online'}}}

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
Expand All @@ -117,7 +119,8 @@ def get_secret(setting, secret=secret):
}
}

redis_host = os.environ.get('REDIS_HOST', 'localhost') # redis host definition
# redis host definition
redis_host = os.environ.get('REDIS_HOST', 'localhost')

# channel layer definitions
CHANNEL_LAYERS = {
Expand Down Expand Up @@ -187,4 +190,4 @@ def get_secret(setting, secret=secret):
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] #static files DIR
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] # static files DIR
4 changes: 2 additions & 2 deletions coding_night_live/views.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from django.shortcuts import render_to_response, render, redirect
from django.template import RequestContext
from django.shortcuts import render

from django.http import HttpResponseRedirect
from django.views.generic.base import TemplateView

# Create your views here.
class MainView(TemplateView):
template_name = 'main.html'

def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect('/services/')
Expand Down
1 change: 1 addition & 0 deletions manage_chat/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class PollAdmin(admin.ModelAdmin):
class ChatAndReplyAdmin(admin.ModelAdmin):
list_display = ('room', '_id', 'time', 'description', 'hash_value', 'is_reply')


admin.site.register(Notice, NoticeAdmin)
admin.site.register(Poll, PollAdmin)
admin.site.register(ChatAndReply, ChatAndReplyAdmin)
4 changes: 1 addition & 3 deletions manage_chat/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@
import json

from django.db import transaction
from channels import Channel, Group
from channels.auth import channel_session_user_from_http, channel_session_user
from channels.auth import channel_session_user

from manage_room.models import Room
from manage_room.consumers import check_admin
from manage_room.utils import get_room_or_error, catch_client_error

Expand Down
20 changes: 10 additions & 10 deletions manage_chat/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def _createHash():
return hash.hexdigest()[:7]

class Notice(models.Model):
room = models.ForeignKey(Room, on_delete=models.CASCADE) #fk
room = models.ForeignKey(Room, on_delete=models.CASCADE)
_id = models.AutoField(primary_key=True)
time = models.DateTimeField(default=timezone.now)
description = models.TextField()
Expand Down Expand Up @@ -65,22 +65,22 @@ def websocket_group(self):

def start_poll(self, label):
final_msg = {
'start_poll': label,
'question': self.question,
'answer': self.answer,
'hash_value': self.hash_value,
'start_poll': label,
'question': self.question,
'answer': self.answer,
'hash_value': self.hash_value,
}
self.websocket_group.send(
{"text": json.dumps(final_msg)}
)

def result_poll(self, label):
final_msg = {
'result_poll': label,
'question': self.question,
'hash_value': self.hash_value,
'answer': self.answer, # json list
'answer_count': self.answer_count, # json list
'result_poll': label,
'question': self.question,
'hash_value': self.hash_value,
'answer': self.answer, # json list
'answer_count': self.answer_count, # json list
}
self.websocket_group.send(
{"text": json.dumps(final_msg)}
Expand Down
7 changes: 0 additions & 7 deletions manage_chat/routing.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
from channels import route
from .consumers import new_chat, new_notice, new_poll, end_poll, get_poll

#websocket_routing = [
# route("websocket.connect", ws_connect),
# route("websocket.receive", ws_receive),
# route("websocket.disconnect", ws_disconnect),
#]

# Websocket command :
custom_routing = [
route("room.receive", new_chat, command="^new_chat$"),
route("room.receive", new_notice, command="^notice$"),
Expand Down
3 changes: 0 additions & 3 deletions manage_chat/tests.py

This file was deleted.

6 changes: 1 addition & 5 deletions manage_chat/views.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
import json

from django.shortcuts import render

from .models import ChatAndReply, Notice, Poll
from manage_room.models import Room

Expand All @@ -24,7 +20,7 @@ def get_notice_list(request):
return notices

def get_poll_list(request):
#request is room's label
# request is room's label
room = Room.objects.get(label=request)

polls = Poll.objects.filter(room=room).order_by('time')
Expand Down
1 change: 1 addition & 0 deletions manage_room/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ class RoomAdmin(admin.ModelAdmin):
class SlideAdmin(admin.ModelAdmin):
list_display = ('title', 'md_blob', 'now_id', 'next_id')


admin.site.register(Room, RoomAdmin)
admin.site.register(Slide, SlideAdmin)
29 changes: 8 additions & 21 deletions manage_room/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

from django.db import transaction
from django.core.cache import cache
from channels import Channel, Group
from channels.auth import channel_session_user_from_http, channel_session_user
from channels import Group
from channels.auth import channel_session_user

from .models import Room, Slide

Expand All @@ -14,27 +14,13 @@
from .diff_match_patch.java_hashcode_conv import javaHash
from .diff_match_patch import diff_match_patch

### Chat channel handling ###

# Channel_session_user loads the user out from the channel session and presents
# it as message.user. There's also a http_session_user if you want to do this on
# a low-level HTTP handler, or just channel_session if all you want is the
# message.channel_session object without the auth fetching overhead.
# Chat channel handling
@channel_session_user
@catch_client_error
def room_join(message):
# Find the room they requested (by ID) and add ourselves to the send group
# Note that, because of channel_session_user, we have a message.user
# object that works just like request.user would. Security!
room = get_room_or_error(message["room"])

# OK, add them in. The websocket_group is what we'll send messages
# to so that everyone in the chat room gets them.
room.websocket_group.add(message.reply_channel)
#message.channel_session['room'] = list(set(message.channel_session['room']).union([room.label]))
# Send a message back that will prompt them to open the room
# Done server-side so that we could, for example, make people
# join rooms automatically.

message.reply_channel.send({
"text": json.dumps({
"join": str(room.label),
Expand All @@ -60,7 +46,7 @@ def room_leave(message):
room = get_room_or_error(message["room"])

room.websocket_group.discard(message.reply_channel)
#message.channel_session['room'] = list(set(message.channel_session['room']).difference([room.label]))
# message.channel_session['room'] = list(set(message.channel_session['room']).difference([room.label]))
# Send a message back that will prompt them to close the room
message.reply_channel.send({
"text": json.dumps({
Expand Down Expand Up @@ -103,7 +89,8 @@ def del_slide(message):
if check_admin(message):
room = get_room_or_error(message["room"])
is_last = Slide.objects.filter(room=room).count()
if is_last <=2:

if is_last <= 2:
raise ClientError("CANNOT_DELETE_LAST")
else:
with transaction.atomic():
Expand Down Expand Up @@ -322,7 +309,7 @@ def check_admin(message):
is_admin = False
if not message.user.is_anonymous():
try:
check_admin = Room.objects.get(admin_user=message.user, label=message["room"])
admin = Room.objects.get(admin_user=message.user, label=message["room"])
is_admin = True
except:
pass
Expand Down
21 changes: 10 additions & 11 deletions manage_room/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json
import allauth

from django.db import models
from django.utils import timezone
Expand All @@ -9,12 +8,12 @@
# Create your models here.

class Room(models.Model):
admin_user = models.ForeignKey(User, on_delete=models.CASCADE) #fk
#admin_user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
#admin_user = models.ForeignKey(allauth.socialaccount.models.SocialAccount, on_delete=models.CASCADE)
admin_user = models.ForeignKey(User, on_delete=models.CASCADE)
# admin_user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
# admin_user = models.ForeignKey(allauth.socialaccount.models.SocialAccount, on_delete=models.CASCADE)

title = models.CharField(max_length=255, default="NoTitle")
link = models.URLField(primary_key=True) #pk
link = models.URLField(primary_key=True)
time = models.DateTimeField(default=timezone.now)

label = models.SlugField(unique=True)
Expand All @@ -34,7 +33,7 @@ def send_title(self, new_title):
self.title = new_title
self.save()

final_msg = {'rename_title': str(self.label), 'title': str(self.title),}
final_msg = {'rename_title': str(self.label), 'title': str(self.title), }

self.websocket_group.send(
{"text": json.dumps(final_msg)}
Expand All @@ -44,10 +43,10 @@ class Slide(models.Model):
room = models.ForeignKey(Room, on_delete=models.CASCADE)
title = models.CharField(max_length=35, default="Unnamed slide")
md_blob = models.TextField(default="")
#id linked list
now_id = models.AutoField(primary_key=True) #pk
next_id = models.PositiveSmallIntegerField(default=0) #if 0: last element
#next_id = models.PositiveSmallIntegerField(unique=True) #if 0: last element
# id ; linked list
now_id = models.AutoField(primary_key=True)
next_id = models.PositiveSmallIntegerField(default=0) # if 0: last element
# next_id = models.PositiveSmallIntegerField(unique=True) # if 0: last element

def __str__(self):
return str(self.now_id)
Expand All @@ -61,7 +60,7 @@ def websocket_group(self):
return Group(self.room.label)

def send_idx(self, command):
final_msg = {command: str(self.now_id),} # Return idx
final_msg = {command: str(self.now_id), } # Return idx

self.websocket_group.send(
{"text": json.dumps(final_msg)}
Expand Down
3 changes: 0 additions & 3 deletions manage_room/tests.py

This file was deleted.

1 change: 0 additions & 1 deletion manage_room/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ def inner(message, *args, **kwargs):
return inner


#def get_room_or_error(room_label, user):
def get_room_or_error(room_label):
"""
Tries to fetch a room for the user, checking permissions along the way.
Expand Down
Loading

0 comments on commit fae839d

Please sign in to comment.