예제 #1
0
def create_private_chat(request, other_user_id):

    pk = None

    other_user = User.objects.get(pk=other_user_id)

    try:

        existing_private_chats = ChatRoom.objects.filter(
            is_direct=True, users__id=request.user.pk)
        matches = existing_private_chats.filter(users__id=int(other_user_id))

        if len(matches):
            pk = matches[0].pk

    except:
        pass

    if not pk:
        chatroom = ChatRoom(name="d_{}_{}".format(request.user.pk,
                                                  other_user.pk),
                            is_direct=True,
                            is_public=False)
        chatroom.save()
        chatroom.users.add(request.user)
        chatroom.users.add(other_user)
        chatroom.save()
        pk = chatroom.pk

    data = {'success': True, 'id': pk}
    return HttpResponse(json.dumps(data))
예제 #2
0
 def clean(self, request, queryset):
     for room in ChatRoom.objects.all():
         room.delete()
     for room in Room.objects.all():
         new = ChatRoom(room_name=room.channel_name[5:],
                        room_url="https://127.0.0.1:8000/chat/" +
                        room.channel_name[5:])
         new.save()
예제 #3
0
 def save(self, **kwargs):
     request = self._context.get('request')
     members = self.validated_data.pop(
         'members') if 'members' in self.validated_data else ''
     self.validated_data['channel_no'] = 'GP_' + str(random.randint(
         2, 9999))
     ct_room = ChatRoom(**self.validated_data)
     self.validated_data['members'] = members
     ct_room.save()
     ct_room.admins.add(request.user.profile)
     ct_room.save()
예제 #4
0
    def post(self, request):
        user_id = request.POST["user_id"]
        chat_type = request.POST["chat_type"]

        customer = User.objects.get(id=user_id)
        name = uuid.uuid4().hex[:16].upper()

        new_chat_room = ChatRoom()
        new_chat_room.name = name
        new_chat_room.customer = customer
        new_chat_room.type = chat_type
        new_chat_room.status = "on_queue"
        new_chat_room.save()

        return JsonResponse({'chat_room_name': name})
예제 #5
0
def create_chat(request):
    if request.method == "POST":
        name = request.POST.get('chat_name')
        created_by = request.user
        token = str(
            int(timezone.now().hour) + int(timezone.now().minute) +
            (int(timezone.now().second) * randint(1, 9))) + (str(
                secrets.token_urlsafe(1))).replace('_', 'M').upper()
        token += str(request.user.id) + str(
            int(timezone.now().day) +
            (int(timezone.now().second) * randint(1, 9))) + (str(
                secrets.token_urlsafe(1))).replace('_', 'A').upper()
        token.replace('-', 'U')
        chat = ChatRoom(name=name, created_by=created_by, token=token)
        chat.save()

    return JsonResponse({})
예제 #6
0
def create_chatroom(request):

    post_data = json.loads(request.body.decode('utf-8'))
    if ('name' not in post_data) or ('publicity' not in post_data):
        data = {'message': "No name or publicity specified.", 'success': False}
        return HttpResponse(json.dumps(data), status=400)
    if (post_data['publicity'] != 'private') and (post_data['publicity'] !=
                                                  'public'):
        data = {'message': "Invalid publicity.", 'success': False}
        return HttpResponse(json.dumps(data), status=400)

    try:

        existing_chatroom = None
        if post_data['publicity'] == 'public':
            existing_chatroom = ChatRoom.objects.get(name=post_data['name'],
                                                     is_public=True)
        else:
            existing_chatroom = ChatRoom.objects.get(name="_private_{}".format(
                post_data['name']),
                                                     is_public=False)

        if existing_chatroom:
            data = {
                'message': "Chatroom with that name already exists.",
                'success': False
            }
            return HttpResponse(json.dumps(data), status=400)
    except:
        pass

    chatroom_name = post_data['name']
    is_public = True
    if post_data['publicity'] == 'private':
        chatroom_name = "_private_{}".format(post_data['private'])
        is_public = False

    chatroom = ChatRoom(name=chatroom_name, is_public=False)
    chatroom.save()
    chatroom.users.add(request.user)
    chatroom.save()

    data = {'id': chatroom.pk, 'message': "Chatroom created.", 'success': True}
    return HttpResponse(json.dumps(data))
예제 #7
0
파일: tests.py 프로젝트: slok/django-chat
    def test_chat_messages(self):
        """Tests the find of the instance in redis"""

        for i in range(30):
            uuid_id = uuid.uuid4()
            cm = ChatMessage(uuid_id, "room1")
            cm.msg = "Python rulz!%d" % i
            cm.user = "******" % i
            cm.time = time.time()
            cm.save()

        cr = ChatRoom("room1")
        messages = cr.messages(10)
        self.assertEqual(len(messages), 10)

        name_number = 20
        for i in messages:
            self.assertEqual(i.user, "slok%d" % name_number)
            name_number += 1
예제 #8
0
def create_room(request, main):
    """
    Create a chat room for a game after going to the index page
    """
    request.user.profile.save()
    name = request.POST.get('Enter a New Room Name')
    try:
        if name.strip():
            request.user.profile.own_room = True
            request.user.profile.save()
            new_room = ChatRoom()
            new_room.name = name
            new_room.owner = request.user.profile
            new_room.main = main
            new_room.save()
            QUEUES[name] = {}
            return redirect('/chat/room/' + str(new_room.pk))
    except IntegrityError, AttributeError:
        pass
예제 #9
0
    def connect(self):
        Room.objects.prune_presences()
        #print("DEBUG : connection")
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name
        self.user = self.scope["user"]
        grp_room = Group.objects.get(name='room_'+self.room_name)
        create = True
        for r in ChatRoom.objects.all():
            if (r.room_name == self.room_group_name[5:]) and (r.room_url =="https://127.0.0.1/chat/"+self.room_group_name[5:] ):
                create = False
        if create == True:
            room_model = ChatRoom(room_name = self.room_group_name[5:],room_url ="https://127.0.0.1/chat/"+self.room_group_name[5:] )
            room_model.save()

        self.user.groups.add(grp_room)
         
        users = []
        for u in grp_room.user_set.all():
            users.append(u.username)
        #print(users)

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        self.room = Room.objects.add(self.room_group_name, self.channel_name, self.user)
        print("Status update")
        num = 0
        for user in self.room.get_users():
            num += 1
            print(user.username + " is connected to chat room " + self.room_group_name)
        print(str(num) + " players in chat room" + self.room_group_name)

        self.accept()
예제 #10
0
def create(request):
    prof = request.user.get_profile()
    err_msg = ""
    if request.method == 'POST':
        form = CreateCompetitionForm(request.POST)
        if form.is_valid() and request.user.is_authenticated():
            # create and save the Competition
            comp = Competition()
            comp.title = form.cleaned_data.get('title')
            comp.host = request.user

            comp.preview_theme = form.cleaned_data.get('preview_theme', False)
            if form.cleaned_data.get('have_theme', False):
                comp.theme = form.cleaned_data.get('theme', '')

            comp.preview_rules = form.cleaned_data.get('preview_rules', False)
            if form.cleaned_data.get('have_rules', False):
                comp.rules = form.cleaned_data.get('rules', '')

            tz_offset = form.cleaned_data.get('tz_offset')
            tz_delta = timedelta(hours=tz_offset)

            comp.start_date = form.cleaned_data.get('start_date') + tz_delta
            comp.submit_deadline = form.cleaned_data.get(
                'submission_deadline_date') + tz_delta

            # calculate vote deadline
            quantity = int(form.cleaned_data.get('vote_time_quantity'))
            quantifier = int(form.cleaned_data.get('vote_time_measurement'))

            comp.vote_period_length = quantity * TimeUnit.seconds_multiplier[
                quantifier]
            vote_period_delta = timedelta(seconds=comp.vote_period_length)

            comp.have_listening_party = form.cleaned_data.get(
                'have_listening_party', True)
            if comp.have_listening_party:
                if form.cleaned_data.get('party_immediately'):
                    comp.listening_party_start_date = comp.submit_deadline
                else:
                    comp.listening_party_start_date = form.cleaned_data.get(
                        'listening_party_date') + tz_delta
                # initialize end date to start date. we make modifications to it
                # when entries are submitted.
                comp.listening_party_end_date = comp.listening_party_start_date

                # this changes whenever listening_party_end_date changes.
                comp.vote_deadline = comp.listening_party_end_date + vote_period_delta
            else:
                comp.vote_deadline = comp.submit_deadline + vote_period_delta

            # create a chatroom for it
            chatroom = ChatRoom()
            chatroom.permission_type = ChatRoom.OPEN
            # open the chat room an hour before the competition
            chatroom.start_date = comp.start_date - timedelta(hours=1)
            # chat room is open an hour before and after competition
            chatroom.end_date = comp.listening_party_end_date + timedelta(
                hours=1)
            chatroom.save()
            comp.chat_room = chatroom

            comp.save()

            # automatically bookmark it
            prof.competitions_bookmarked.add(comp)
            prof.save()

            return HttpResponseRedirect(reverse("arena.home"))
    else:
        initial = {
            'have_theme': True,
            'have_rules': True,
            'preview_rules': True,
            'have_listening_party': True,
            'party_immediately': True,
            'vote_time_quantity': 1,
            'vote_time_measurement': TimeUnit.WEEKS,
        }
        form = CreateCompetitionForm(initial=initial)

    return render_to_response('arena/create.html',
                              locals(),
                              context_instance=RequestContext(request))
예제 #11
0
def request_item_view(request, ids):
    print("Enter exchange/request_item_view")
    if request.method != "GET":
        raise Http404
    ids = ids.split(" ")

    # double check the url data
    if len(ids) != 2 or not ids[0].isnumeric() or not ids[1].isnumeric():
        raise Http404

    myItemId, itemId = int(ids[0]), int(ids[1])

    # check if the ids are valid
    if ExchangeItem.objects.filter(pk=myItemId).count() == 0 or \
       ExchangeItem.objects.filter(pk=myItemId).count() ==0:
        raise Http404

    # ids.append(roomname)
    # sendrequest.delay(" ".join(ids))

    myItem = ExchangeItem.objects.get(pk=myItemId)
    user = request.user
    userEmail = user.email

    otherItem = ExchangeItem.objects.get(pk=itemId)
    owner = otherItem.user
    ownerEmail = owner.email

    roomname = generateRandomCode(ROOMNAME_LENGTH)
    chatroom = ChatRoom(user1=user, user2=owner, roomname=roomname)
    chatroom.save()

    # update both item status
    myItem.request.add(otherItem)
    if myItem.status < 1:
        myItem.status = 1
    if otherItem.status < 1:
        otherItem.status = 1
    myItem.save()
    otherItem.save()

    context = {
        "name": otherItem.name,
        "id": otherItem.pk,
        "description": otherItem.description,
        "price": otherItem.price,
        "status": otherItem.status,
        "item": otherItem,
        "owner": otherItem.user
    }
    # master
    # context = {"name": otherItem.name,
    #            "id": otherItem.pk,
    #            "description": otherItem.description,
    #            "price": otherItem.price,
    #            "status": otherItem.status,
    #            "owner": otherItem.user,
    #            "item": otherItem,
    #            "myItem": myItem}
    #            master

    print(userEmail, ownerEmail)
    msg1 = """Hi {0},\n\n
             User {1} would like to exchange for your "{2}" with "{3}".\n
             Accept this request if you are interested!\n
             You can contact {1} through:\n
             1. SwapSpace's chatroom at http://74739114.ngrok.io/chat, enter code <{5}> to start chatting!\n
             2. Or at {4}. Thanks!""".format(owner, user, otherItem, myItem,
                                             userEmail, roomname)
    sendEmail(ownerEmail, "request", msg1)

    msg2 = """Hi {0},\n\n
             Your exchange request for "{1}" with your "{2}" has been sent successfully!\n
             To follow up this request, \n
             1. SwapSpace's chatroom at http://74739114.ngrok.io/chat, enter code <{4}> to start chatting!\n
             2. Or at {3}. Thanks!""".format(user, otherItem, myItem,
                                             ownerEmail, roomname)
    sendEmail(userEmail, "request", msg2)

    return redirect(reverse('item_detail', kwargs={'id': otherItem.pk}))