Пример #1
0
    def who_is_online(self):
        """
        Gross hack to determine who from the chat room is online.
        TODO (brian): Eventually convert this feature via WebSocket
            connection via consumers.py.  Don't have time to fix now.

        Precondition:
            Detail Room/Chat view is called

        Postcondition:
            2 tuples will be return containing the status of their
            activity within the last 15 minutes

        Parameters:
            None

        Returns:
            (list, list): tuple of 2 lists.  The first list will contain
                a list of people in the room active within the last 15
                minutes.  The second list are members in the room who
                were not active within the last 15 minutes.
        """
        weird_user_objects = OnlineUserActivity.get_user_activities()
        all_online_users = [item.user for item in weird_user_objects]
        online_users = []
        offline_users = []
        for user in self.members:
            if user in all_online_users:
                online_users.append(user)
            else:
                offline_users.append(user)
        return online_users, offline_users
Пример #2
0
def index(request):
    # Redirect to active game
    user = request.user
    game_object = Game.get_active_game(user)
    if game_object is not None:
        return HttpResponseRedirect("/game/")

    # Get user activity
    user_activity_objects = OnlineUserActivity.get_user_activities(
        timedelta(minutes=3))
    online = list(user for user in user_activity_objects)
    online.sort(key=lambda x: x.user.email, reverse=False)

    # Get friendlist
    friendlist = Friends.get_friends_for(request.user)

    # Get unanswered requests
    userRequestList = UserRequests.get_unanswered_for(request.user)

    # Get gamelist
    gamelist = Game.objects.all()

    # Get announcements
    announcements = Announcements.get_announcements_last_hour()

    # Render page
    return render(
        request, "lobby/lobby.html", {
            "user": request.user,
            "onlinelist": online,
            "friendlist": friendlist,
            "userRequestList": userRequestList,
            "gamelist": gamelist,
            "announcements": announcements
        })
Пример #3
0
    def get_friends_for(target):
        # Get all friends relations
        friends = Friends.objects.all()

        # Get online users
        user_activity_objects = OnlineUserActivity.get_user_activities(
            datetime.timedelta(minutes=5))
        onlinelist = (user for user in user_activity_objects)

        user_activity_objects = OnlineUserActivity.get_user_activities(
            datetime.timedelta(minutes=10))
        awaylist = (user for user in user_activity_objects)

        # Prepare result
        result = dict()

        # Process relations
        for friend in friends:
            target = friend.user1 if target == friend.user2 else friend.user2

            status = None

            if not target.is_authenticated:
                status = "offline"

            if status is None:
                for online_user in onlinelist:
                    if online_user.user == target:
                        status = "online"
                        break

            if status is None:
                for away_user in awaylist:
                    if away_user.user == target:
                        status = "away"
                        break

            if status is None:
                status = "offline"

            result[target] = status

        # End result
        return result
Пример #4
0
def ajax_online_list(request):
    # Get user activity
    user_activity_objects = OnlineUserActivity.get_user_activities(
        timedelta(minutes=3))
    online = list(user for user in user_activity_objects)
    online.sort(key=lambda x: x.user.email, reverse=False)
    return render(request, "lobby/user-list.html", {
        "onlinelist": online,
        "currentUser": request.user
    })
Пример #5
0
def online(request):
    user_activity_objects = OnlineUserActivity.get_user_activities(
        timedelta(seconds=1))
    users = (user for user in user_activity_objects)
    # for i in users:
    #     onlineusers = i.user
    return render(request, 'test.html', context={"users": users})


# def home_page_view(request):
#     return render(request,'index.html')
Пример #6
0
def chat_view(request):
    """Render the template with required context variables"""
    if not request.user.is_authenticated:
        return redirect('accounts-api:login')
    if request.method == "GET":
        user_activity_objects = OnlineUserActivity.get_user_activities(
            timedelta(minutes=60))
        active_users = (user for user in user_activity_objects)
        return render(
            request, 'chat.html', {
                'users': User.objects.exclude(username=request.user.username),
                'active_users': active_users
            })
Пример #7
0
def blog(request):
    page = request.GET.get('page')

    user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=15))
    onliners = (user for user in user_activity_objects)

    try:
        posts = Post.objects.all().order_by('-time_last_commented')

        paginator = Paginator(posts, 100)

        try:
            posts_slice = paginator.page(page)
        except PageNotAnInteger:
            posts_slice = paginator.page(1)
        except EmptyPage:
            posts_slice = paginator.page(paginator.num_pages)


        if request.user.is_authenticated:
            logout=True
            username = request.user.username
            user_id = request.user.id
            is_authenticated = True
            has_private = request.user.profile.has_private
        else:
            username = ''
            logout=False
            user_id = -1
            is_authenticated = False
            has_private = False
    except Exception as e:
            has_private = False
            username = ''
            logout=False
            user_id = -1
            is_authenticated = False
            posts_slice = []

    return render(request, 'blog.html',{'home':'blog.html',
                                         'user': request.user,
                                         'username': username,
                                         'has_private': has_private,
                                         'posts': posts_slice, 
                                         'current_page': 'blog',
                                         'is_authenticated': is_authenticated,
                                         'logout': logout,
                                         'user_id': user_id})
Пример #8
0
def simple_signin(request):

    user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=15))
    onliners = (user for user in user_activity_objects)
 
    try:
        loves = Emotion.objects.filter(attitude_id=1)
        mehs = Emotion.objects.filter(attitude_id=2)
        hates = Emotion.objects.filter(attitude_id=3)

        username = request.POST.get('uname')
        password = request.POST.get('psw')
        user = authenticate(username=username, password=password)
        login(request, user, backend='custom.users.backends.LocalBackend') #the user is now logged in
 

        if request.user.is_authenticated:
            logout=True
            user_id = user.id
            username = user.username
            is_authenticated = True
            has_private = request.user.profile.has_private
        else:
            logout=False
            user_id = -1
            username = ''
            is_authenticated = False
            has_private = False
    except Exception as e:
            log = Logger(log="SOMETHING WENT WRONG {}".format(e))
            log.save()
            username = ''
            logout = False
            user_id = -1
            user = request.user
            is_authenticated = False
            has_private = False

    return render(request, 'index.html',{'home':'index.html',
                                         'user': user,
                                         'loves': loves,
                                         'mehs': mehs,
                                         'hates': hates,
                                         'has_private': has_private,
                                         'username': user.username,
                                         'is_authenticated': is_authenticated,
                                         'logout': logout,
                                         'user_id': user.id})
Пример #9
0
def user_profile(request, user_id):
    user = User.objects.get(id=user_id)
    current_user = request.user
    profile = Profile.objects.get(user_id=user_id)
    server = profile.get_game_server_display()
    race = profile.get_game_race_display()
    user_activity_objects = OnlineUserActivity.get_user_activities(
        timedelta(minutes=3))
    online_status = True if user in (
        user.user for user in user_activity_objects) else False
    subscribers_count = len(
        UserSubscriber.objects.filter(subscription=user_id))
    subscriptions_count = len(UserSubscriber.objects.filter(user=user_id))
    subscription_status = len(
        UserSubscriber.objects.filter(subscription=user_id, user=current_user))
    groups_count = len(GroupSubscriber.objects.filter(user=user_id))
    posts_list = UserPost.objects.filter(author=user).order_by('-date_pub')
    posts = []
    for post in posts_list:
        files = UserPostFeedFile.objects.filter(feed=post.id)
        images = []
        others = []
        for file in files:
            if is_image(file.file):
                images.append(file)
            else:
                others.append(file)
        posts.append((post, images, others))

    return render(request,
                  'social_network_app/profile.html',
                  context={
                      'profile': profile,
                      'user': user,
                      'current_user': current_user,
                      'server': server,
                      'race': race,
                      'online_status': online_status,
                      'subscribers': subscribers_count,
                      'subscriptions': subscriptions_count,
                      'groups': groups_count,
                      'subscription_status': subscription_status,
                      'posts': posts
                  })
Пример #10
0
    def get_unanswered_for_game_online(recipient):
        userQuery = Q(recipient=recipient)
        answeredQuery = Q(answered=False)
        typeQuery = Q(type="game")

        # Check if user is online
        dataset = UserRequests.objects.filter(
            userQuery & answeredQuery & typeQuery).order_by("time_sent")
        result = list()
        # Get online users
        user_activity_objects = OnlineUserActivity.get_user_activities(
            datetime.timedelta(minutes=5))
        onlinelist = [user.user for user in user_activity_objects]
        # Filter online users
        for data in dataset:
            if data.sender in onlinelist and data.is_recent():
                result.append(data)

        return result
Пример #11
0
def forum(request):
    page = request.GET.get('page')
    loves = None
    mehs = None
    hates = None

    user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=15))
    onliners = list(user for user in user_activity_objects)


    try:
        loves = Emotion.objects.filter(attitude_id=1).order_by('-time_published')
        mehs = Emotion.objects.filter(attitude_id=2).order_by('-time_published')
        hates = Emotion.objects.filter(attitude_id=3).order_by('-time_published')
        total_loves = len(loves)
        total_mehs = len(mehs)
        total_hates = len(hates)
    except Exception as e:
        pass

    loves_chunked = list(chunks(loves, 50))
    loves_chunked_length = len(loves_chunked)
    mehs_chunked = list(chunks(mehs, 50))
    mehs_chunked_length = len(mehs_chunked)
    hates_chunked = list(chunks(hates, 50))
    hates_chunked_length = len(hates_chunked)
    index = max([loves_chunked_length, mehs_chunked_length, hates_chunked_length])

    pages = []
    pages_loves = []
    pages_hates = []
    pages_mehs = []

    for i in range(0, index):
        try:
            pages_loves.append(loves_chunked[i])
        except Exception as e:
            pages_loves.append([])
        try:
            pages_mehs.append(mehs_chunked[i])
        except Exception as e:
            pages_mehs.append([])
        try:
            pages_hates.append(hates_chunked[i])
        except Exception as e:
            pages_hates.append([])

    for i in range(0, index):
        p = Page(pages_loves[i], pages_mehs[i], pages_hates[i])
        pages.append(p)

    paginator = Paginator(pages, 1) # Show 25 contacts per page

    try:
        if request.user.is_authenticated:
            logout=True
            user_id = request.user.id
            username = request.user.username
            is_authenticated = True
            has_private = request.user.profile.has_private
        else:
            logout=False  
            user_id = -1
            username = ''
            is_authenticated = False
            has_private = False
    except Exception as e:
            username = ''
            logout=False
            user_id = -1
            is_authenticated = False
            has_private = False

    paginator1 = Paginator(loves, 50)
    paginator2 = Paginator(mehs, 50)
    paginator3 = Paginator(hates, 50)

    try:
        meh_slice = paginator2.page(page)
    except PageNotAnInteger:
        meh_slice = paginator2.page(1)
    except EmptyPage:
        meh_slice = paginator2.page(paginator2.num_pages)
    except Exception:
        meh_slice = []

    try:
        love_slice = paginator1.page(page)
    except PageNotAnInteger:
        love_slice = paginator1.page(1)
    except EmptyPage:
        love_slice = paginator1.page(paginator1.num_pages)
    except Exception:
        love_slice = []
 

    try:
        hate_slice = paginator3.page(page)
    except PageNotAnInteger:
        hate_slice = paginator3.page(1)
    except EmptyPage:
        hate_slice = paginator3.page(paginator3.num_pages)
    except Exception:
        hate_slice = []


  
    try:
        pages_slice = paginator.page(page)
    except PageNotAnInteger:
        pages_slice = paginator.page(1)
    except EmptyPage:
        pages_slice = paginator.page(paginator4.num_pages)
 
    return render(request, 'forum.html',{'home':'forum.html', 
                                         'user': request.user,
                                         'pages': pages_slice,
                                         'loves': love_slice,
                                         'mehs': meh_slice,
                                         'onliners': onliners,
                                         'hates': hate_slice,
                                         'current_page': 'forum',
                                         'has_private': has_private,
                                         'username': username,
                                         'is_authenticated': is_authenticated,
                                         'logout': logout,
                                         'user_id': user_id})
Пример #12
0
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        sender = self.user
        context = text_data_json["context"]

        if context == "request_reject":
            # Treat message as rejecting request
            rtype = text_data_json["type"]

            if rtype == "game" or rtype == "friend":
                req_id = text_data_json["request_id"]
                req_object = UserRequests.objects.filter(id=req_id).first()

                if req_object is None:
                    self.send(text_data=json.dumps({"request_new_ack": "reject_missing"}))
                    return

                if self.user_object != req_object.recipient:
                    self.send(text_data=json.dumps({"request_new_ack": "reject_permission"}))
                    return

                # Reject request
                req_object.answered = True
                req_object.answer = False
                req_object.save()

                # Notify sender and recipient
                self.send(text_data=json.dumps({"request_new_ack": "request_reject", "request_id": req_object.id}))

                # Notify sender that request was rejected
                target_group = "requests_user_" + str(req_object.sender.id)
                req_type = ""

                if req_object.type == "friend":
                    req_type = "o přátelství"
                elif req_object.type == "game":
                    req_type = "o hru"

                async_to_sync(self.channel_layer.group_send)(
                    target_group,
                    {
                        "type": "request_notify_reject",
                        "message": "Tvůj požadavek " + req_type + " s " + req_object.recipient.email + " byl odmítnut",
                        "request_id": req_object.id,
                        "rtype": "friend",
                    }
                )

                return

        # Route based on context
        if context == "request_accept":
            # Treat message as accepting request
            rtype = text_data_json["type"]

            if rtype == "game":
                req_id = text_data_json["request_id"]
                req_object = UserRequests.objects.filter(id=req_id).first()

                # Request doesnt exist
                if req_object is None:
                    self.send(text_data=json.dumps({"request_new_ack": "accept_missing"}))
                    return

                # Request is wrong type
                if req_object.type != "game":
                    self.send(text_data=json.dumps({"request_new_ack": "wrong_type"}))
                    return

                # Block user from accepting request that isnt for him
                if self.user_object != req_object.recipient:
                    self.send(text_data=json.dumps({"request_new_ack": "accept_permission"}))
                    return

                # Get online users
                user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=3))
                online = (user.user.id for user in user_activity_objects)

                # User is not online
                if not req_object.recipient.id in online:
                    self.send(text_data=json.dumps({"request_new_ack": "not_online"}))
                    return

                # Check if sender is in game
                sending = self.user_object

                if Game.has_active_game(sending):
                    self.send(text_data=json.dumps({"request_new_ack": "already_game_self"}))
                    return

                # Check if recipient is in game
                if Game.has_active_game(req_object.recipient):
                    self.send(text_data=json.dumps({"request_new_ack": "already_game"}))
                    return

                # Create game
                game_object = Game.create_game(req_object.sender, req_object.recipient)

                # Notify players
                target_recipient = "requests_user_" + str(game_object.player1.id)
                target_sender = "requests_user_" + str(game_object.player2.id)

                async_to_sync(self.channel_layer.group_send)(
                    target_recipient,
                    {
                        "type": "request_notify_game",
                        "request_new_ack": "game_start",
                        "game_id": game_object.id,
                    }
                )

                async_to_sync(self.channel_layer.group_send)(
                    target_sender,
                    {
                        "type": "request_notify_game",
                        "request_new_ack": "game_start",
                        "game_id": game_object.id,
                    }
                )

                ann = Announcements()
                ann.text = "Uživatelé " + str(game_object.player1.email) + " a " + str(
                    game_object.player2.email) + " začali hru #" + str(game_object.id) + "."
                ann.save()

                return

            if rtype == "friend":
                req_id = text_data_json["request_id"]
                req_object = UserRequests.objects.filter(id=req_id).first()

                if req_object.type != "friend":
                    self.send(text_data=json.dumps({"request_new_ack": "wrong_type"}))
                    return

                if req_object is None:
                    self.send(text_data=json.dumps({"request_new_ack": "accept_missing"}))
                    return

                if self.user_object != req_object.sender and self.user_object != req_object.recipient:
                    self.send(text_data=json.dumps({"request_new_ack": "accept_permission"}))
                    return

                # Set request responded true and positive
                req_object.answered = True
                req_object.answer = True
                req_object.save()

                # Create friend
                friend = Friends()
                friend.user1 = req_object.sender
                friend.user2 = req_object.recipient
                friend.save()

                # Announcement create
                ann = Announcements()
                ann.text = "Uživatelé " + str(friend.user1.email) + " a " + str(friend.user2.email) + " se stali přáteli."
                ann.save()

                # Notify rejecter to delete his record
                self.send(text_data=json.dumps({"request_new_ack": "request_accept", "request_id": req_object.id}))
                return

        if context == "request_new":
            # Treat message as new request
            rtype = text_data_json["type"]

            # Further route based on type
            if rtype == "game":
                # Treat request as new game request

                # Acknowledge request
                self.send(text_data=json.dumps({"request_new_ack": "acknowledged"}))

                # Get recipient
                id = text_data_json["recipient"]
                recipient = User.objects.filter(id=id).first()
                target_group = "requests_user_" + str(recipient.id)

                # Check if user wants to play game with himself
                if recipient == self.user_object:
                    self.send(text_data=json.dumps({"request_new_ack": "game_self"}))
                    return

                # Get online users
                user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=3))
                online = (user.user.id for user in user_activity_objects)

                # User is not online
                if not recipient.id in online:
                    self.send(text_data=json.dumps({"request_new_ack": "not_online"}))
                    return

                # Check if recipient have pending request
                if UserRequests.has_pending_request(self.user_object, recipient, rtype):
                    self.send(text_data=json.dumps({"request_new_ack": "already_pending"}))
                    return

                other_side_requests = UserRequests.get_pending_request(recipient, self.user_object, rtype)

                # Check if sender is in game
                sending = self.user_object
                active_game_self = Game.get_active_game(sending)

                if active_game_self is not None:
                    self.send(text_data=json.dumps({"request_new_ack": "already_game_self", "game_id": active_game_self.id}))
                    return

                # Check if recipient is in game
                if Game.has_active_game(recipient):
                    self.send(text_data=json.dumps({"request_new_ack": "already_game"}))
                    return

                # Check pending request from other side
                if len(other_side_requests) > 0:
                    request_object = other_side_requests[0]

                    # Notify other user
                    async_to_sync(self.channel_layer.group_send)(
                        target_group,
                        {
                            "type": "request_notify_merged",
                            "request_new_ack": "merged",
                            "request_id": other_side_requests[0].id,
                            "rtype": "game",
                        }
                    )
                    # Notify self
                    self.send(text_data=json.dumps({
                        "request_new_ack": "merged",
                        "request_id": request_object.id,
                    }))

                    # Set request responded true and positive
                    request_object.answered = True
                    request_object.answer = True
                    request_object.save()

                    # Create game
                    game_object = Game.create_game(request_object.sender, request_object.recipient)

                    # Notify players
                    target_recipient = "requests_user_" + str(game_object.player1.id)
                    target_sender = "requests_user_" + str(game_object.player2.id)

                    async_to_sync(self.channel_layer.group_send)(
                        target_recipient,
                        {
                            "type": "request_notify_game",
                            "request_new_ack": "game_start",
                            "game_id": game_object.id,
                        }
                    )

                    async_to_sync(self.channel_layer.group_send)(
                        target_sender,
                        {
                            "type": "request_notify_game",
                            "request_new_ack": "game_start",
                            "game_id": game_object.id,
                        }
                    )

                    # Terminate rest of function
                    return

                # Actually create Request in database
                request_text = "Uživatel " + self.user + " tě požádal o hru!"
                request = UserRequests.create_request(self.user_object, recipient, "game", request_text)

                # Send request to recipient
                async_to_sync(self.channel_layer.group_send)(
                    target_group,
                    {
                        "type": "request_notify",
                        "message": request_text,
                        'sender_name': self.user,
                        "sender": self.user_id,
                        "request_id": request.id,
                        "rtype": "game",
                    }
                )
                return
            if rtype == "friend":
                # Treat request as new friend request

                # Acknowledge request
                self.send(text_data=json.dumps({"request_new_ack": "acknowledged"}))

                # Get recipient
                id = text_data_json["recipient"]
                recipient = User.objects.filter(id=id).first()
                target_group = "requests_user_" + str(recipient.id)

                # Check if user wants to friend himself
                if recipient == self.user_object:
                    self.send(text_data=json.dumps({"request_new_ack": "friends_self"}))
                    return

                # Check if users are already friends
                if Friends.are_friends(self.user_object, recipient):
                    self.send(text_data=json.dumps({"request_new_ack": "already_friends"}))
                    return

                # Check if recipient have pending request
                if UserRequests.has_pending_request(self.user_object, recipient, rtype):
                    self.send(text_data=json.dumps({"request_new_ack": "already_pending"}))
                    return

                other_side_requests = UserRequests.get_pending_request(recipient, self.user_object, rtype)

                # Check pending request from other side
                if len(other_side_requests) > 0:
                    request_object = other_side_requests[0]

                    # Notify other user
                    async_to_sync(self.channel_layer.group_send)(
                        target_group,
                        {
                            "type": "request_notify_merged",
                            "request_new_ack": "merged",
                            "request_id": other_side_requests[0].id,
                        }
                    )
                    # Notify self
                    self.send(text_data=json.dumps({
                        "request_new_ack": "merged",
                        "request_id": request_object.id,
                    }))

                    # Set request responded true and positive
                    request_object.answered = True
                    request_object.answer = True
                    request_object.save()

                    # Create friend
                    friend = Friends()
                    friend.user1 = self.user_object
                    friend.user2 = recipient
                    friend.save()

                    ann = Announcements()
                    ann.text = "Uživatelé " + str(friend.user1.email) + " a " + str(
                        friend.user2.email) + " se stali přáteli."
                    ann.save()

                    # Terminate rest of function
                    return

                # Actually create Request in database
                request_text = "Uživatel " + self.user + " tě požádal o přátelství!"
                request = UserRequests.create_request(self.user_object, recipient, "friend", request_text)

                # Send request to recipient
                async_to_sync(self.channel_layer.group_send)(
                    target_group,
                    {
                        "type": "request_notify",
                        "message": request_text,
                        'sender_name': self.user,
                        "sender": self.user_id,
                        "request_id": request.id,
                        "rtype": "friend",
                    }
                )
Пример #13
0
 def test_get_active_users__users_out_of_timedelta(self):
     online_users = OnlineUserActivity.get_user_activities(
         timedelta(minutes=1))
     self.assertEqual(online_users.count(), 1)
Пример #14
0
 def get_active_user_count():
     last_hour = timedelta(minutes=60)
     return OnlineUserActivity.get_user_activities(last_hour).count()
Пример #15
0
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        action = text_data_json["action"]

        # TODO: check time between last player action
        # Something like a hello message with answer everything is OK
        # and if not just stop game
        if action == "keep_alive":
            # Get all users active last 5 minutes
            user_activity_objects = OnlineUserActivity.get_user_activities(datetime.timedelta(minutes=5))
            onlinelist = [user.user for user in user_activity_objects]

            # Check if both users are still online
            if self.game.player1 not in onlinelist or self.game.player2 not in onlinelist:
                # Inform remaining players
                async_to_sync(self.channel_layer.group_send)(
                    self.room_group_name,
                    {
                        'type': 'game_notify_end',
                        'action': "game_completed",
                        "winner": "draw",
                    }
                )
                # End game - draw
                self.game.completed = True
                self.game.save()

                ann = Announcements()
                ann.text = "Hra " + str(self.game.id) + " mezi " + str(self.game.player1.email) + " a " + str(self.game.player2.email) + " skončila remízou"
                ann.save()

            else:
                # Send OK
                self.send(text_data=json.dumps({
                    "keep_alive": "ok",
                }))

        # Notify game abandon
        if action == "game_abandon":
            # Winner of game is other user
            winner = self.game.player2 if self.user == self.game.player1 else self.game.player2

            # Notify everyone about end of game
            async_to_sync(self.channel_layer.group_send)(
                self.room_group_name,
                {
                    'type': 'game_notify_end',
                    'action': "game_completed",
                    "winner": winner.email,
                }
            )

            # Mark game as completed
            self.game.completed = True
            # Set winner
            self.game.winner = winner
            # Save game to database
            self.game.save()

            ann = Announcements()
            ann.text = "Hra " + str(self.game.id) + " mezi " + str(self.game.player1.email) + " a " + str(
                self.game.player2.email) + " skončila vítězstvím " + str(self.game.winner.email) + "."
            ann.save()


        # Request game state action
        if action == "load":
            # Get all actions for game
            all_game_actions = GameAction.objects.filter(game=self.game).order_by("-date")

            all_game_actions_dict = dict()
            counter = 0
            for game_action in all_game_actions:
                symbol = "x" if game_action.who == self.game.player1 else "o"
                all_game_actions_dict[counter] = {
                    "x": game_action.x,
                    "y": game_action.y,
                    "symbol": symbol,
                }
                counter = counter + 1

            # Add action
            all_game_actions_dict["action"] = "load"

            # Send every action
            self.send(text_data=json.dumps(all_game_actions_dict))
            return

        # Claim field in grid action
        if action == "claim":
            # Get last game action
            last_action = GameAction.objects.filter(game=self.game).order_by("-date").first()
            player_turn = None
            player_turn_symbol = None

            # If there are no actions, player1 starts
            if last_action is None:
                player_turn = self.game.player1
                player_turn_symbol = "x"
            else:
                # Player1 played last so player2 play now
                if last_action.who == self.game.player1:
                    player_turn = self.game.player2
                    player_turn_symbol = "o"
                # Player2 played last so player1 play now
                else:
                    player_turn = self.game.player1
                    player_turn_symbol = "x"

            # Check if right player tries to CLAIM
            if self.user != player_turn:
                self.send(text_data=json.dumps({
                    "action": "claim_ack",
                    "status": "ERR",
                    "status_message": "Nejsi na řadě!",
                }))
                return

            # Its player turn - get info sent
            coordX = text_data_json["x"]
            coordY = text_data_json["y"]

            # Check if coords are not used yet
            coord_action = GameAction.objects.filter(game=self.game, x=coordX, y=coordY).first()
            if coord_action is not None:
                self.send(text_data=json.dumps({
                    "action": "claim_ack",
                    "status": "ERR",
                    "status_message": "Dané políčko je již zabráno!",
                }))
                return

            # Coords are not used, claim them
            new_action = GameAction()
            new_action.game = self.game
            new_action.x = coordX
            new_action.y = coordY
            new_action.who = self.user
            new_action.save()

            # Notify both players
            async_to_sync(self.channel_layer.group_send)(
                self.room_group_name,
                {
                    'type': 'game_notify_claimed',
                    'action': "claimed",
                    'x': coordX,
                    "y": coordY,
                    "symbol": player_turn_symbol,
                }
            )

            # Check if game ended - BFS from current location
            wd = WinDetector(coordX, coordY, self.game, self.user)
            win = wd.detected_win()

            if wd.detected_win() is not None:
                self.game.completed = True
                self.game.winner = self.user
                self.game.save()

                ann = Announcements()
                ann.text = "Hra " + str(self.game.id) + " mezi " + str(self.game.player1.email) + " a " + str(
                    self.game.player2.email) + " skončila vítězstvím " + str(self.game.winner.email) + "."
                ann.save()

                # Notify everyone of game end
                async_to_sync(self.channel_layer.group_send)(
                    self.room_group_name,
                    {
                        'type': 'game_notify_end',
                        'action': "game_completed",
                        "winner": self.user.email,
                    }
                )
Пример #16
0
 def test_get_active_users(self):
     online_users = OnlineUserActivity.get_user_activities(
         timedelta(minutes=6))
     self.assertEqual(online_users.count(), 2)
Пример #17
0
def renderOnline(request):
    onlines = OnlineUserActivity.get_user_activities()
    number = onlines.count()
    return render(request, 'online.html', {'online': onlines, 'count': number})
Пример #18
0
 def test_get_active_users_ordering(self):
     online_users = OnlineUserActivity.get_user_activities(
         timedelta(minutes=60))
     self.assertEqual(online_users.count(), 2)
     self.assertEqual(list(online_users),
                      [self.online_user1, self.online_user2])
def main_page(request, forbidden = '', usr = None):
    error_message = ''
    nothing = 'false'
    threading.Thread(target=update).start()
    forbidden = forbidden
    if forbidden:
        if forbidden == 'forbidden':
            error_message = 'К сожалению, это предложение устарело!'
        else:
            if forbidden == 'own':
                error_message = 'Ответить на свое предложение невозможно!'
    mainbalance = 0.0
    balance = ''
    if not request.user.is_anonymous:
        wallets = Wallet.objects.filter(user=request.user)
        for w in wallets:
            mainbalance += float(w.btcbalance)
        balance = str(mainbalance) + ' BTC'
        finishdate = datetime.datetime.now() - datetime.timedelta(hours=1, minutes=30)
        for ans in Reply.objects.filter(user=request.user):
            if ans.time < finishdate.time():
                proffer = ans.proffer
                proffer.replies_count = proffer.replies_count - 1
                proffer.save()
                if ans.thread:
                    thread = Thread.objects.filter(id=ans.thread.id)
                    thread.delete()
                ans.delete()

    online_users = []
    from datetime import timedelta
    user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=60))
    active_users = (user for user in user_activity_objects)
    for u in active_users:
        online_users.append(u.user)
    user = request.user
    searchoff = 'true'
    search_form = None
    test = None
    bank = ''
    rate = 0
    count = 15
    mode = 'КУПЛЮ'
    search_table =  ProffersTable(Proffer.objects.all())
    #orders_ltc = OrdersTable(Order.objects.filter(offer_type__contains="LTC").exclude(state="Draft"))
    #orders_xmr = OrdersTable(Order.objects.filter(offer_type__contains="XMR").exclude(state="Draft"))
    #orders_dash = OrdersTable(Order.objects.filter(offer_type__contains="DASH").exclude(state="Draft"))
    #orders_eth = OrdersTable(Order.objects.filter(offer_type__contains="ETH").exclude(state="Draft"))
    #orders_zec = OrdersTable(Order.objects.filter(offer_type__contains="ZEC").exclude(state="Draft"))
    #orders_btc = OrdersTable(Order.objects.filter(offer_type__contains="BTC").exclude(state="Draft"))
    proffers_ltc = ProffersTable(Proffer.objects.filter(type_of_token__contains="LTC").exclude(state="Draft"))
    proffers_xmr = ProffersTable(Proffer.objects.filter(type_of_token__contains="XMR").exclude(state="Draft"))
    proffers_dash = ProffersTable(Proffer.objects.filter(type_of_token__contains="DASH").exclude(state="Draft"))
    proffers_eth = ProffersTable(Proffer.objects.filter(type_of_token__contains="ETH").exclude(state="Draft"))
    proffers_zec = ProffersTable(Proffer.objects.filter(type_of_token__contains="ZEC").exclude(state="Draft"))
    if usr:
        proffers_btc_buy = ProffersTable(Proffer.objects.filter(user=usr, type_of_token__contains="BTC", type='КУПЛЮ').exclude(state="Draft")[::-1])
        proffers_btc_sale = ProffersTable(
            Proffer.objects.filter(user=usr, type_of_token__contains="BTC", type='ПРОДАМ').exclude(state="Draft")[::-1])
    else:
        proffers_btc_buy = ProffersTable(
            Proffer.objects.filter(type_of_token__contains="BTC", type='КУПЛЮ').exclude(state="Draft")[::-1])
        proffers_btc_sale = ProffersTable(
            Proffer.objects.filter(type_of_token__contains="BTC", type='ПРОДАМ').exclude(state="Draft")[::-1])
    search_form = SearchForm()
    for obj in Proffer.objects.all():
        sum = 0
        for wlt in Wallet.objects.filter(user=obj.user):
             sum += float(wlt.btcbalance)
        obj.balance = sum * obj.rate
        obj.save()
    if request.method == 'POST':
        if "buy_more" in request.POST:
            proffers_btc_sale = ProffersTable(
                Proffer.objects.filter(type_of_token__contains="BTC", type='ПРОДАМ').exclude(state="Draft"))
        if "sale_more" in request.POST:
            proffers_btc_buy = ProffersTable(
                Proffer.objects.filter(type_of_token__contains="BTC", type='КУПЛЮ').exclude(state="Draft"))
        search_form = SearchForm(request.POST)
        if search_form.is_valid():
            rate = search_form.data['rate']
            bank = search_form.cleaned_data['bank_search']
            searchoff = 'false'
            if 'buybutton' in search_form.data:
                mode = 'КУПЛЮ'
            else:
                mode = 'ПРОДАМ'
            if Proffer.objects.filter(max__gte=int(rate), min__lte=int(rate), bank__contains=bank, type=mode).count() == 0:
                nothing = 'true'
            else:
                search_table = ProffersTable(Proffer.objects.filter(max__gte=int(rate), min__lte=int(rate), bank__contains=bank, type=mode ))

    return render(request, 'index_main.html', {


                                           'proffers_ltc': proffers_ltc, 'proffers_xmr': proffers_xmr,
                                           'proffers_dash': proffers_dash, 'proffers_eth': proffers_eth,
                                           'proffers_zec': proffers_zec, 'proffers_btc_buy': proffers_btc_buy,
                                               'proffers_btc_sale': proffers_btc_sale,
                                               'search_table':search_table,
                                           'user':user,
                                               'searchoff':searchoff,
                                               'search_form':search_form,
                                               'bank':bank,
                                               'rate':rate,
                                               'mode':mode,
                                               'online_users':online_users,
                                               'balance':balance,
                                               'forbidden':forbidden,
                                               'error_message':error_message,
                                               'nothing':nothing
                                           })