예제 #1
0
 def createData(self):
     u = User.objects.create_user(username='******',
                                  first_name='aa',
                                  last_name='bb',
                                  password='******')
     u2 = User.objects.create_user(username='******',
                                   first_name='bb',
                                   last_name='bb',
                                   password='******')
     r = Room(name='a', createdBy=u)
     r.save()
     Room(name='b', createdBy=u).save()
     for i in range(5):
         Message(content='content ' + str(i),
                 writer=u if i % 2 else u2,
                 room=r).save()
예제 #2
0
파일: views.py 프로젝트: saby95/CrowdMentor
def claim(request, task_id):
    user = User.objects.get(username=request.user.username)
    try:
        task = ResearchTasks.objects.get(pk=task_id)
    except ResearchTasks.DoesNotExist:
        raise Http404("Task does not exist")
    tuj_count = TaskUserJunction.objects.filter(worker_id=user,
                                                task_id=task).count()
    if tuj_count != 0:
        messages.warning(
            request, 'Permission Denied!! You already have claimed the task')
        return HttpResponseRedirect('/')
    task.num_workers -= 1
    tuj = TaskUserJunction()
    tuj.worker_id = user
    tuj.task_id = task
    room = Room(title=tuj, staff_only=False)
    room.save()
    tuj.room_id = room.id
    tuj.save()
    task.save()
    user.profile.claimed_tasks += 1
    user.profile.save()
    # print(user.profile.completed_tasks)
    messages.info(request, 'New Task Claimed')
    return HttpResponseRedirect('/tasks/')
예제 #3
0
    def createRoom(num_players):
        room_name = get_random_string(30)

        r = Room(n_demanded=num_players, room_name=room_name, n_connected=1)
        r.save()

        return r
예제 #4
0
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(self.room_group_name,
                                           self.channel_name)

        try:
            room = Room.objects.get(name=self.room_name)
        except Room.DoesNotExist:
            room = None

        print("$$$$$$$$11 : ", room)

        if room is None:
            room = Room(name=self.room_name,
                        label='test_label',
                        cnt_member='1')
            room.save()
        else:
            print("######1 room.cnt_member : ", room.cnt_member)
            room.cnt_member += 1
            room.save()
            print("######2 room.cnt_member : ", room.cnt_member)

        await self.accept()
예제 #5
0
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name ='empty'
        if self.scope["user"].is_anonymous:
            self.close()
            return
        self.username = self.scope["user"].username
        if self.checked_privacy():

            try:
                self.room = Room.objects.get(name=self.room_name)
            except ObjectDoesNotExist:
                self.room = Room(name=self.room_name)
                self.room.save()

            self.room_name = self.room_name.replace('|','_')
            self.room_group_name = 'chat_%s' % self.room_name

            # Join room group
            async_to_sync(self.channel_layer.group_add)(
                self.room_group_name,
                self.channel_name
            )

            self.accept()
예제 #6
0
 async def get(self):
     room_name = self.request.match_info['room'].lower()
     room = Room(self.request.app['db_cursor'], room_name)
     is_room_in = await room.check_room()
     if not is_room_in:
         redirect(self.request, 'chat')
     else:
         session = await get_session(self.request)
         return {'room_name': str(room_name), 'rooms': self.request.app['rooms'], 'user_name': str(session["user"])}
예제 #7
0
	def handle(self, *args, **options):
		#Django 1.6 South
		#python manage.py schemamigration chat $1 --initial
		#python manage.py syncdb --all
		#python manage.py migrate --fake
		call_command('makemigrations', 'chat')
		call_command('migrate')
		Room(id=ALL_ROOM_ID, name=ALL_REDIS_ROOM).save()
		# call_command('syncdb')
예제 #8
0
	def create_new_room(self, message):
		room_name = message[VarNames.ROOM_NAME]
		if not room_name or len(room_name) > 16:
			raise ValidationError('Incorrect room name "{}"'.format(room_name))
		room = Room(name=room_name)
		self.do_db(room.save)
		RoomUsers(room_id=room.id, user_id=self.user_id).save()
		subscribe_message = self.subscribe_room_channel_message(room.id, room_name)
		self.publish(subscribe_message, self.channel, True)
예제 #9
0
    def create(self, request, pk=None):
        if 'name' not in request.session or not request.session[
                'authenticated']:
            return Response({
                'success': False,
            }, status=401)

        if 'display_name' not in request.data:
            return Response({
                'message': 'Nie podano nazwy.',
                'success': False
            },
                            status=400)

        admin = Profile.objects.get(name=request.session['name'])

        if 'image' in request.data:
            room = Room(admin=admin,
                        display_name=request.data['display_name'],
                        image=request.data['image'],
                        name=base58.random(8))
        else:
            room = Room(admin=admin,
                        display_name=request.data['display_name'],
                        name=base58.random(8))

        room.save()
        room.participants.set([admin])

        data = RoomSerializer(room).data
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            f'user-{request.session["name"]}', {
                "type": "subscribe.room",
                "data": data,
            })

        return Response({
            'success': True,
            'room': {
                'id': room.id,
                'name': room.name
            }
        })
예제 #10
0
def create_other_room_wo_check(self_user_id, user_id):
	room = Room()
	room.save()
	room_id = room.id
	if self_user_id == user_id:
		RoomUsers(user_id=user_id, room_id=room_id).save()
	else:
		RoomUsers.objects.bulk_create([
			RoomUsers(user_id=self_user_id, room_id=room_id),
			RoomUsers(user_id=user_id, room_id=room_id),
		])
	return room_id
예제 #11
0
def accept(request):
    user = request.user
    id = request.GET.get("id")
    row = Contract.objects.get(id=id)
    row.accepted = "1"
    row.save()

    whom = row.user_id
    room = Room(who=user.id, whom=whom)
    room.save()

    return JsonResponse({'results': True})
예제 #12
0
def create_self_room(self_user_id, user_rooms):
	room_ids = list([room['room_id'] for room in evaluate(user_rooms)])
	query = execute_query(settings.SELECT_SELF_ROOM, [room_ids, ])
	if query:
		room_id = query[0]['room__id']
		update_room(room_id, query[0]['room__disabled'])
	else:
		room = Room()
		room.save()
		room_id = room.id
		RoomUsers(user_id=self_user_id, room_id=room_id, notifications=False).save()
	return room_id
예제 #13
0
    async def post(self):
        data = await self.request.post()
        name = str(data.get('room_name'))
        room = Room(self.request.app['db_cursor'], name)
        result = await room.create_room()
        if not result:
            redirect(self.request, 'chat')
        else:
            if room not in self.request.app['rooms']:
                self.request.app['rooms'].append(room)

            redirect_to_room(self.request, f"{data.get('room_name')}")
예제 #14
0
    def create(self, validated_data):
        room = Room(
            name=validated_data.pop('name'),
            public=validated_data.pop('public'),
            max_retrieve_count=validated_data.pop('max_retrieve_count'))

        room.save()

        users_data = validated_data.pop('users')
        for user_data in users_data:
            UserInRoom.objects.create(room=room, **user_data)

        return room
예제 #15
0
    def post(self, request):
        user_1 = self.request.user
        user_name = json.loads(request.POST.get("user_2"))
        user_2 = User.objects.get(username=user_name)
        rooms = Room.objects.filter(user_1=user_1, user_2=user_2)
        if not rooms:
            rooms = Room.objects.filter(user_1=user_2, user_2=user_1)

        if not rooms:
            room = Room(user_1=user_1, user_2=user_2)
            room.save()
        else:
            room = rooms[0]

        return JsonResponse({"room_name": room.room_name})
예제 #16
0
def request_chat(request):
    try:
        user = request.user
        whom = request.GET.get('id')
        is_room = Room.objects.filter(
            who=user.id, whom=whom) | Room.objects.filter(who=whom,
                                                          whom=user.id)
        if is_room.count() > 0:
            return JsonResponse({'results': True})
        else:
            row = Room(who=user.id, whom=whom)
            row.save()
            return JsonResponse({'results': True})
    except:
        return JsonResponse({'results': False})
예제 #17
0
    def test_insert_message_for_existing_room(self):
        """ Test Message insertion code """

        room_name = "Room1"

        r = Room(name=room_name)
        r.save()

        message = "Hello"
        user = "******"

        m = self.service.insert_message(room_name, message, user)

        self.assertEqual(m.room.name, room_name)
        self.assertEqual(m.message, message)
        self.assertEqual(m.user, user)
예제 #18
0
def create_other_room(self_user_id, user_id, user_rooms):
	rooms_query = RoomUsers.objects.filter(user_id=user_id, room__in=user_rooms)
	query = rooms_query.values('room__id', 'room__disabled')
	try:
		room = do_db(query.get)
		room_id = room['room__id']
		update_room(room_id, room['room__disabled'])
	except RoomUsers.DoesNotExist:
		room = Room()
		room.save()
		room_id = room.id
		RoomUsers.objects.bulk_create([
			RoomUsers(user_id=self_user_id, room_id=room_id),
			RoomUsers(user_id=user_id, room_id=room_id),
		])
	return room_id
예제 #19
0
파일: views.py 프로젝트: xiaoqiao99/chat
def index(request):
    # from channels.layers import get_channel_layer
    # from asgiref.sync import async_to_sync
    # channel_layer = get_channel_layer()
    # async_to_sync(channel_layer.group_send)(
    #     "chat_lobby",
    #     {
    #         'type': 'chat.message',
    #         'message': "6666666yyyyy66666666"
    #     }
    # )

    # r = Room.objects.filter(id=46).update(name="33333333") # 如果信号中使用post_save 此更新不会出发信号机制
    r = Room()
    r.name = "xiao"
    r.label = "qq "
    r.save()
    return render(request, 'chat/index.html', {})
예제 #20
0
def follow(request):
    try:
        if request.session['user'] is None:
            return render(request, 'account/dashboard.html',
                          {'section': 'dashboard'})
    except KeyError:
        return render(request, 'account/dashboard.html',
                      {'section': 'dashboard'})
    if request.method == "POST":
        user1 = request.session['user']
        user2 = request.POST.get("username")
        user1 = Users.objects.filter(username=user1)
        user2 = Users.objects.filter(username=user2)
        chat_id1 = hash_chat_id(user1[0], user2[0])
        chat_id2 = hash_chat_id(user2[0], user1[0])
        does_exist1 = Room.objects.filter(name=chat_id1)
        if does_exist1.__len__() > 0:
            chat_id = chat_id1
        else:
            does_exist2 = Room.objects.filter(name=chat_id2)
            if does_exist2.__len__() > 0:
                chat_id = chat_id2
            else:
                chat_id = chat_id1

        try:
            follow = Followers(user1=user1[0], user2=user2[0], chat_id=chat_id)
            follow.save()
        except:
            pass
        try:
            room = Room(name=chat_id,
                        description="Say Hi to you buddy",
                        slug=chat_id)
            room.save()
        except:
            pass
    all_users = [
        x.username
        for x in Users.objects.exclude(username=request.session['user'])
    ]
    return render(request, 'account/users.html', {'all_users': all_users})
예제 #21
0
def generate_room(data):
    user = User.query.filter_by(username=data['username']).first()
    room = Room()
    room.name = data['room_name']

    user.rooms.append(room)

    db.session.commit()

    message = Message(
        user_id=user.id,
        room_id=room.id,
        content=f"{user.username} just created room <b>{room.id}</b>")

    db.session.add(message)

    db.session.commit()

    socketio.emit('room_created_sucessfully', {'room_id': room.id, \
                                                'room_name':room.name \
                                                }, to=request.sid)
예제 #22
0
 def handle(self, *args, **options):
     """
     ...
     """
     # rooms
     rooms_instances = [Room(name=f'name_{number}') for number in range(4)]
     Room.objects.bulk_create(rooms_instances)
     # messages
     messages_room_1_instances = [
         Message(
             text=f'text{number}',
             room_id=1,
         ) for number in range(4)
     ]
     messages_room_2_instances = [
         Message(
             text=f'text{number}',
             room_id=2,
         ) for number in range(3)
     ]
     Message.objects.bulk_create(messages_room_1_instances)
     Message.objects.bulk_create(messages_room_2_instances)
예제 #23
0
def product_view(request, id):
    product = get_object_or_404(Product, id=id)

    img_slides = product.images.all()

    if request.POST.get("delete"):
        product.delete()
        return redirect("/")

    if request.POST.get("chat"):
        if Room.objects.filter(user_1=request.user, user_2=product.seller) or Room.objects.filter(user_1=product.seller, user_2=request.user):
            return redirect("/chat/"+request.user.username+product.seller.username)
        else:
            chat = Room(room_name=request.user.username+product.seller.username, user_1=request.user, user_2=product.seller)
            chat.save()
            return redirect("/chat/"+request.user.username+product.seller.username)

    context = {
        'user': request.user,
        'product': product,
        'img_slides': img_slides,
    }
    return render(request, 'store/product_view.html', context)
예제 #24
0
	def create_room(self, user_rooms, user_id):
		if self.user_id == user_id:
			room_ids = list([room['room_id'] for room in user_rooms])
			query_res = self.execute_query(SELECT_SELF_ROOM, [room_ids, ])
		else:
			rooms_query = Room.users.through.objects.filter(user_id=user_id, room__in=user_rooms)
			query_res = rooms_query.values('room__id', 'room__disabled')
		if len(query_res) > 0:
			room = query_res[0]
			room_id = room['room__id']
			self.update_room(room_id, room['room__disabled'])
		else:
			room = Room()
			room.save()
			room_id = room.id
			if self.user_id == user_id:
				RoomUsers(user_id=self.user_id, room_id=room_id).save()
			else:
				RoomUsers.objects.bulk_create([
					RoomUsers(user_id=user_id, room_id=room_id),
					RoomUsers(user_id=self.user_id, room_id=room_id),
				])
		return room_id
예제 #25
0
파일: views.py 프로젝트: erfanhs/bitko
def createRoom(request):
    user = request.user
    room_name = request.data.get('room_name')
    password = request.data.get('room_password')
    if not room_name:
        return Response({'error': 'room name is required !'}, status=400)
    if not roomName_validator.search(room_name):
        return Response({'error': 'invalid room name !'}, status=400)
    try:
        Room.objects.get(room_name=room_name)
        return Response({'error': 'this room name is already taken !'}, status=400)
    except Room.DoesNotExist:
        room = Room(room_name=room_name)
        if password:
            if len(password) < 6:
                return Response({'error': 'password must be more than 5 characters !'}, status=400)
            room.password = roomsPasswordHasher(password)
        room.creator = user
        room.save()
        room.users.add(user)
        room.save()
    serializer = RoomSerializer(room)
    print(serializer.data)
    return Response(serializer.data)
예제 #26
0
def generate_room():
    return Room(name=Faker().word())
예제 #27
0
    def create_new_room(self, message):
        room_name = message.get(VarNames.ROOM_NAME)
        users = message.get(VarNames.ROOM_USERS)
        channel_id = message.get(VarNames.CHANNEL_ID)
        users.append(self.user_id)
        users = list(set(users))
        if room_name and len(room_name) > 16:
            raise ValidationError('Incorrect room name "{}"'.format(room_name))
        create_room = True
        if not room_name and len(users) == 2:
            user_rooms = evaluate(
                Room.users.through.objects.filter(
                    user_id=self.user_id,
                    room__name__isnull=True).values('room_id'))
            user_id = users[0] if users[1] == self.user_id else users[1]
            try:
                room = RoomUsers.objects.filter(user_id=user_id,
                                                room__in=user_rooms).values(
                                                    'room__id',
                                                    'room__disabled').get()
                room_id = room['room__id']
                if room['room__disabled']:  # only a private room can be disabled
                    Room.objects.filter(id=room_id).update(
                        disabled=False, p2p=message[VarNames.P2P])
                    RoomUsers.objects.filter(
                        user_id=self.user_id, room_id=room_id).update(
                            volume=message[VarNames.VOLUME],
                            notifications=message[VarNames.NOTIFICATIONS])
                else:
                    raise ValidationError('This room already exist')
                create_room = False
            except RoomUsers.DoesNotExist:
                pass
        elif not room_name:
            raise ValidationError(
                'At least one user should be selected, or room should be public'
            )

        if channel_id and channel_id not in self.get_users_channels_ids():
            raise ValidationError("You don't have access to this channel")
        if channel_id:
            channel = Channel.objects.get(id=channel_id)
            channel_name = channel.name
            channel_creator_id = channel.creator_id
        else:
            channel_name = None
            channel_creator_id = None
        if create_room:
            room = Room(name=room_name,
                        channel_id=channel_id,
                        p2p=message[VarNames.P2P])
            if not room_name:
                room.creator_id = self.user_id
            room.save()
            room_id = room.id
            max_id = Message.objects.all().aggregate(Max('id'))['id__max']
            ru = [
                RoomUsers(user_id=user_id,
                          room_id=room_id,
                          last_read_message_id=max_id,
                          volume=message[VarNames.VOLUME],
                          notifications=message[VarNames.NOTIFICATIONS])
                for user_id in users
            ]
            RoomUsers.objects.bulk_create(ru)

        m = {
            VarNames.EVENT: Actions.CREATE_ROOM,
            VarNames.ROOM_ID: room_id,
            VarNames.ROOM_USERS: users,
            VarNames.CB_BY_SENDER: self.id,
            VarNames.INVITER_USER_ID: self.user_id,
            VarNames.HANDLER_NAME: HandlerNames.CHANNELS,
            VarNames.VOLUME: message[VarNames.VOLUME],
            VarNames.P2P: message[VarNames.P2P],
            VarNames.NOTIFICATIONS: message[VarNames.NOTIFICATIONS],
            VarNames.ROOM_NAME: room_name,
            VarNames.TIME: get_milliseconds(),
            VarNames.JS_MESSAGE_ID: message[VarNames.JS_MESSAGE_ID],
        }
        if channel_id:
            m[VarNames.CHANNEL_NAME] = channel_name
            m[VarNames.CHANNEL_ID] = channel_id
            m[VarNames.CHANNEL_CREATOR_ID] = channel_creator_id
        jsoned_mess = encode_message(m, True)
        for user in users:
            self.raw_publish(jsoned_mess, RedisPrefix.generate_user(user))
예제 #28
0
def room(request, first=None, second=None):

    if first == second == request.user.pk:
        return redirect('chat_index')

    me = first
    other = second

    dialogs_info = []
    rooms = request.user.rooms.all()

    for user_room in rooms:
        for user in user_room.users.all():
            if user != request.user:
                dialog_user = user

        me = request.user.pk
        other = dialog_user.pk
        dialog_label = user_room.label
        dialog_room = Room.objects.get(label=dialog_label)
        dialog_message_instance = dialog_room.messages.all().last()
        if dialog_message_instance:
            dialog_message = dialog_message_instance.message
            dialog_message_timestamp = dialog_message_instance.timestamp
        else:
            dialog_message = ''
            dialog_message_timestamp = ''
        dialogs_info.append({
            'dialog_image_url': dialog_user.profile.image.url,
            'dialog_message': dialog_message[:50],
            'dialog_message_timestamp': dialog_message_timestamp,
            'dialog_user_first_name': dialog_user.first_name,
            'dialog_label': dialog_label,
            'dialog_me': me,
            'dialog_other': other,
        })
    dialogs_info = sorted(dialogs_info, key=lambda x: x['dialog_message_timestamp'], reverse=True)

    try:
        first_user = User.objects.get(pk=int(first))
        second_user = User.objects.get(pk=int(second))
        if first_user and second_user and first_user != second_user:
            room_name_1 = f'{first_user.pk}_{second_user.pk}'
            room_name_2 = f'{second_user.pk}_{first_user.pk}'
            try:
                chat_room = Room.objects.get(label=room_name_1)
                room_name = room_name_1

            except Room.DoesNotExist:
                try:
                    chat_room = Room.objects.get(label=room_name_2)
                    room_name = room_name_2

                except Room.DoesNotExist:
                    chat_room = Room(label=room_name_1)
                    room_name = room_name_1
                    chat_room.save()

            chat_room.users.add(first_user)
            chat_room.users.add(second_user)

            if first_user == request.user:
                me = first_user
                other = second_user
            elif second_user == request.user:
                me = second_user
                other = first_user

            chat_messages = reversed(chat_room.messages.order_by('-timestamp')[:50])

            context = {
                'room_name': room_name,
                'room': chat_room,
                'rooms': rooms,
                'chat_messages': chat_messages,
                'me': me,
                'other': other,
                'dialogs_info': dialogs_info,
            }
            return render(request, 'chat/room.html', context)
    except (TypeError, ValueError) as e:
        context = {
            'dialogs_info': dialogs_info,
        }
        return render(request, 'chat/room.html', context)
예제 #29
0
    def create_new_room(self, message):
        room_name = message.get(VarNames.ROOM_NAME)
        users = message.get(VarNames.ROOM_USERS)
        users.append(self.user_id)
        users = list(set(users))
        if room_name and len(room_name) > 16:
            raise ValidationError('Incorrect room name "{}"'.format(room_name))
        create_user_rooms = True
        if not room_name and len(users) == 2:
            user_rooms = evaluate(
                Room.users.through.objects.filter(
                    user_id=self.user_id,
                    room__name__isnull=True).values('room_id'))
            user_id = users[0] if users[1] == self.user_id else users[1]
            try:
                room = RoomUsers.objects.filter(user_id=user_id,
                                                room__in=user_rooms).values(
                                                    'room__id',
                                                    'room__disabled').get()
                room_id = room['room__id']
                if room['room__disabled']:
                    Room.objects.filter(id=room_id).update(disabled=False)
                else:
                    raise ValidationError('This room already exist')
                create_user_rooms = False
            except RoomUsers.DoesNotExist:
                pass
        elif not room_name:
            raise ValidationError(
                'At least one user should be selected, or room should be public'
            )
        if create_user_rooms:
            room = Room(name=room_name)
            do_db(room.save)
            room_id = room.id
            max_id = Message.objects.all().aggregate(Max('id'))['id__max']
            ru = [
                RoomUsers(user_id=user_id,
                          room_id=room_id,
                          last_read_message_id=max_id,
                          volume=message[VarNames.VOLUME],
                          notifications=message[VarNames.NOTIFICATIONS])
                for user_id in users
            ]
            RoomUsers.objects.bulk_create(ru)

        m = {
            VarNames.EVENT: Actions.CREATE_ROOM_CHANNEL,
            VarNames.ROOM_ID: room_id,
            VarNames.ROOM_USERS: users,
            VarNames.CB_BY_SENDER: self.id,
            VarNames.INVITER_USER_ID: self.user_id,
            VarNames.HANDLER_NAME: HandlerNames.CHANNELS,
            VarNames.VOLUME: message[VarNames.VOLUME],
            VarNames.NOTIFICATIONS: message[VarNames.NOTIFICATIONS],
            VarNames.ROOM_NAME: room_name,
            VarNames.TIME: get_milliseconds(),
            VarNames.JS_MESSAGE_ID: message[VarNames.JS_MESSAGE_ID],
        }
        jsoned_mess = encode_message(m, True)
        for user in users:
            self.raw_publish(jsoned_mess, RedisPrefix.generate_user(user))
예제 #30
0
 def test_default_test(self):
     room = Room()
     self.assertEqual(room.title, '')