def mutate(self, info, post_id): errors = list() redirect = False room = None profile = info.context.user.active_profile match = None try: match = Post.objects.get(id=post_id) match.liked_by.add(profile) profile.favorite_posts.add(match) match.save() new_like.send(sender=None, profile=match.profile) except ObjectDoesNotExist: errors.append('Match with specified ID does not exists.') receiver_profile = match.profile receiver_liked_by = receiver_profile.who_liked_matches sender_liked_by = profile.who_liked_matches if receiver_profile in sender_liked_by and profile in receiver_liked_by and not Room.exists(receiver_profile.id, profile.id, match.id): room = Room.objects.create(post=match) room.users.add(profile) room.users.add(receiver_profile) room.save() redirect = True posts_matched.send(sender=match.__class__, matched_post=match) elif Room.exists(receiver_profile.id, profile.id, match.id): room = Room.get_by_users(receiver_profile.id, profile.id) return LikePostMutation(errors=errors, room=room, redirect=redirect)
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
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()
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/')
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()
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
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})
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
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
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})
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})
def resolve_has_room(self, info): profile = info.context.user.active_profile receiver_profile = self.profile if Room.exists(profile.id, receiver_profile.id, self.id): return True return False
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()
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
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)
def create_room(request, display_name, participants: str): participants_list = [request.user.profile] for p in participants.split(";"): try: participant = Profile.objects.get(user__username=p) participants_list.append(participant) except Profile.DoesNotExist: return JsonResponse({"error": f"{p} was not found."}) try: Room.create_room(display_name, participants_list) except Exception as e: return JsonResponse({"error": e}) return JsonResponse({"success": "Room created."})
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')
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)
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"])}
async def test_room_list(self): await self.app.objects.create(Room) resp = await self.client.request('GET', '/chat/rooms/') assert resp.status == 200 data = await resp.text() data = json.loads(data) count = len(await self.app.objects.execute(Room.select())) assert data.get('count') == count
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})
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')}")
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)
async def post(self): """ Check is roomname unique and create new User """ roomname = await self.is_valid() if not roomname: redirect(self.request, 'create_room') if await self.request.app.objects.count(Room.select().where( Room.name**roomname)): add_message(self.request, 'danger', f'Room with {roomname} already exists.') redirect(self.request, 'create_room') room = await self.request.app.objects.create(Room, name=roomname) redirect(self.request, 'room', parts=dict(slug=room.name))
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()
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)
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
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)
def mutate(self, info, room_input): room = None errors = list() post_id = room_input['post_id'] post = Post.objects.get(id=post_id) sender = info.context.user.active_profile receiver = post.profile if Room.exists(sender.id, receiver.id, post_id): errors.append('Room for this post already exists.') return CreateRoomMutation(room=room, errors=errors) room = Room.objects.create(post_id=post_id) room.users.add(receiver) room.users.add(sender) room.save() new_listing_response.send(sender=None, profile=receiver) return CreateRoomMutation(room=room, errors=errors)
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)
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', {})