async def get_liked_people(self,
                               item_id: int,
                               owner_id: int = 0) -> Response:
        """A function that returns information about people who liked the post with the specified id.

        :param item_id: Post id relative to owner_id.
        :type: int

        :param owner_id: Id of wall owner.
        :type: int

        :return: Dictionary with operation status and user list.
        :rtype: Response
        """
        try:
            likes_people = self.api.likes.getList(
                type='post',
                owner_id=owner_id,
                item_id=item_id,
            )
            user_ids = [user_id for user_id in likes_people['items']]
            return Response(status=ResponseStatus.OK,
                            likes=user_ids,
                            response_type=ResponseTypes.LIKES)
        except vk.exceptions.VkAPIError as e:
            return Response(status=ResponseStatus.EXTERNAL_ERROR,
                            reason=f'Error in get_liked_people: {str(e)}',
                            response_type=ResponseTypes.ERROR)
    async def wrapper(view: web.View) -> web.Response:
        url = urlparse(str(view.request.url))
        query_params = parse_qs(url.query)
        try:
            token = query_params['token'][0]
        except KeyError as e:
            view.request.app['logger'].error("Token not found: " + str(e))
            token = None

        if token in view.request.app['users']:
            view.request.app['logger'].info("User logged in via token.")
            response = await func(view, token)
        elif url.scheme == 'ws':
            view.request.app['logger'].info(
                "User authentication error when connect via WebSocket.")
            response = web.WebSocketResponse()
            await response.prepare(view.request)
            await response.send_json(
                Response(status=ResponseStatus.SERVER_ERROR,
                         reason="Not valid token, login please.",
                         response_type=ResponseTypes.ERROR))
        else:
            view.request.app['logger'].info(
                "User authentication error when connect via HTTP.")
            response = web.json_response(
                Response(status=ResponseStatus.SERVER_ERROR,
                         reason="Not authenticated token, login please.",
                         response_type=ResponseTypes.ERROR))

        return response
    async def get_info(
            self,
            user_ids: list = None,
            fields:
        str = 'relation, bdate, photo_200_orig, nickname, online, sex, city, home_town',
            filters: dict = None) -> Response:
        """The function allows you to take extended information about users.

        :param filters: Dictionary of filters for filter fields of users
        :type: dict

        :param user_ids: List of user ids about which you need to get extended information.
        :type: list

        :param fields: Set of fields (VK Api) to return in response. Example: "field1, field2".
        :type: str
        """
        try:
            print(user_ids)
            users = self.api.users.get(user_ids=user_ids, fields=fields)
            users = user_filter(
                users=users, filters=filters) if filters is not None else users

            return Response(status=ResponseStatus.OK,
                            info=users,
                            response_type=ResponseTypes.USERS_INFO)
        except vk.exceptions.VkAPIError as e:
            return Response(status=ResponseStatus.EXTERNAL_ERROR,
                            reason=f'Error in get_info: {str(e)}',
                            response_type=ResponseTypes.ERROR)
    async def get_friends(self,
                          target_id: int = 0,
                          fields: str = '') -> Response:
        """The function allows you to take information about friends of target user.

        :param target_id: Id of target user.
        :type: int

        :param fields: Set of fields (VK Api) to return in response. Example: "field1, field2".
        :type: str

        :return: A dictionary with the status of the operation and the result of its execution.
        :rtype: Response
        """
        try:
            friends = self.api.friends.get(user_id=target_id, fields=fields)
            print(friends)
            return Response(status=ResponseStatus.OK,
                            friends=friends,
                            response_type=ResponseTypes.FRIENDS_LIST)
        except vk.exceptions.VkAPIError as e:
            return Response(status=ResponseStatus.EXTERNAL_ERROR,
                            reason=f'Error in get_friends: {str(e)}',
                            response_type=ResponseTypes.ERROR)
        except AttributeError as e:
            return Response(status=ResponseStatus.SERVER_ERROR,
                            reason='Error in get_friends: Not authenticated',
                            response_type=ResponseTypes.ERROR)
    async def auth(self, credentials: dict) -> Response:
        """User authentication function through VK API.

        Initializes vk_session and vk_api.

        :param credentials: Dictionary with E-Mail or phone by login key, and password by password key.
        :type: dict

        :return: Dictionary with status operations and initialized objects vk_api and vk_session.
        :rtype: Response
        """
        try:
            self.session = vk.AuthSession(
                app_id=config['vk_api_app_id'],
                user_login=credentials['login'],
                user_password=credentials['password'])

            self.api = vk.API(self.session,
                              v=config.get('vk_api_version'),
                              lang=config.get('vk_api_lang'),
                              timeout=config.getint('vk_api_timeout'))
            return Response(status=ResponseStatus.OK,
                            response_type=ResponseTypes.AUTH_TOKEN)
        except vk.exceptions.VkAuthError as e:
            return Response(status=ResponseStatus.EXTERNAL_ERROR,
                            reason=f'Error in auth: {str(e)}',
                            response_type=ResponseTypes.ERROR)
        except KeyError:
            return Response(status=ResponseStatus.SERVER_ERROR,
                            reason="Lack of login or password",
                            response_type=ResponseTypes.ERROR)
    async def get_commented_peoples(self,
                                    post_id: int,
                                    owner_id: int = 0) -> Response:
        """A function that returns information about people who commented the post with the specified id.

        :param item_id: Post id relative to owner_id.
        :type: int

        :param owner_id: Id of wall owner.
        :type: int

        :return: Dictionary with operation status and user list.
        :rtype: Response
        """
        try:
            commented_people = self.api.wall.getComments(owner_id=owner_id,
                                                         post_id=post_id,
                                                         extended=1)
            user_ids = [user['id'] for user in commented_people['profiles']]
            return Response(status=ResponseStatus.OK,
                            commented=user_ids,
                            response_type=ResponseTypes.COMMENTS)
        except vk.exceptions.VkAPIError as e:
            return Response(status=ResponseStatus.EXTERNAL_ERROR,
                            reason=f'Error in get_commented_people: {str(e)}',
                            response_type=ResponseTypes.ERROR)
 async def get_last_post(self, owner_id: int = 0) -> Response:
     try:
         post = self.api.wall.get(owner_id=owner_id, count=1)
         return Response(status=ResponseStatus.OK,
                         post=str(post),
                         response_type=ResponseTypes.LAST_POST)
     except vk.exceptions.VkAPIError as e:
         return Response(status=ResponseStatus.EXTERNAL_ERROR,
                         reason=f'Error in get_last_post: {str(e)}',
                         response_type=ResponseTypes.ERROR)
 async def get_profileinfo(self):
     try:
         info = self.api.account.getProfileInfo()
         print(info)
         return Response(status=ResponseStatus.OK,
                         info=info,
                         response_type=ResponseTypes.USERS_INFO)
     except vk.exceptions.VkAPIError as e:
         return Response(status=ResponseStatus.EXTERNAL_ERROR,
                         reason=f'Error in get_profileinfo: {str(e)}',
                         response_type=ResponseTypes.ERROR)
예제 #9
0
    async def post(self, token: str) -> web.Response:
        """The function allows you to take information about the users who liked the given post.

        :param token: Token of current user.
        :type: str

        :return: JSON response with result information.
        :rtype: web.Response
        """
        try:
            request = await self.request.json()
            owner_id, item_id = request['url'].split('wall')[1].split(
                '_')  # /wall{owner_id}_{item_id}
            filters = request['filterKit']
            print(f'Filters: {filters}')
        except Exception:
            self.request.app['logger'].error("URL parse error.")
            return web.json_response(
                Response(status=ResponseStatus.SERVER_ERROR,
                         reason="URL parse error.",
                         response_type=ResponseTypes.ERROR))
        api = self.request.app['users'][token]
        user_ids = await api.get_liked_people(
            owner_id=owner_id,
            item_id=item_id,
        )
        print(f"Liked users: {user_ids.get('likes')}")
        result = await api.get_info(user_ids=user_ids.get('likes'),
                                    filters=filters)
        self.request.app['logger'].info("HTTPGetLikedPeoples.get called.")

        return json_response(result)
예제 #10
0
    async def post(self) -> web.Response:
        """HTTP Decorators Feature.

        :return: JSON response with result information.
        :rtype: web.Reponse
        """
        data = await self.request.json()
        try:
            vk_api = VkAPI()
            credentials = {
                'login': data['login'],
                'password': data['password']
            }
            self.request.app['logger'].info(credentials)
            result = await vk_api.auth(credentials=credentials)
            self.request.app['users'][vk_api.session.access_token] = vk_api
            self.request.app['logger'].info("User logged in via HTTPLogin.")
        except KeyError as e:
            self.request.app['logger'].error("Lack of login or password: "******"Lack of login or password",
                         token='NULL',
                         response_type=ResponseTypes.ERROR))
        except AttributeError as e:
            self.request.app['logger'].error("Authentication failed: " +
                                             str(e))
            return web.json_response(
                Response(status=ResponseStatus.SERVER_ERROR,
                         reason='VK Authentication failed.',
                         token='NULL',
                         response_type=ResponseTypes.ERROR))

        if result.is_error():
            self.request.app['logger'].error(result)
            result['token'] = 'NULL'
            return web.json_response(result)

        return web.json_response(
            Response(status=result['status'],
                     token=vk_api.session.access_token,
                     response_type=ResponseTypes.AUTH_TOKEN))
예제 #11
0
    async def get(self) -> web.WebSocketResponse:
        """HTTP Decorators Feature.

        :return: JSON response with result information.
        :rtype: web.WebSocketResponse
        """
        ws = WSResponse()
        await ws.prepare(self.request)
        self.request.app['logger'].info("User connected in via WebScoket.")
        self.request.app['websockets'].append(ws)

        async for msg in ws:
            if msg.type != WSMsgType.ERROR:
                json_request = json.loads(str(msg.data, encoding='utf-8'))
                print(json_request)
                try:
                    password = str(base64.b64decode(
                        bytes(json_request.get('password'), 'utf-8')),
                                   encoding='utf-8')
                    print(password)
                    vk_api = VkAPI()
                    credentials = {
                        'login': json_request['login'],
                        'password': password
                    }
                    result = await vk_api.auth(credentials=credentials)
                    self.request.app['logger'].info(credentials)
                    if result.is_error():
                        self.request.app['logger'].error(result)
                        await ws.send_json(data=result)
                    else:
                        self.request.app['users'][
                            vk_api.session.access_token] = vk_api
                        self.request.app['logger'].error(
                            "User logged in via WebScoket.")
                        await ws.send_json({
                            'status': result['status'],
                            'token': vk_api.session.access_token
                        })
                except KeyError as e:
                    self.request.app['logger'].error(
                        f"WSLogin.get error: {str(e)}.")
                    await ws.send_json(
                        Response(status=ResponseStatus.SERVER_ERROR,
                                 reason=str(e),
                                 response_type=ResponseTypes.ERROR))

            else:
                self.request.app['logger'].error(
                    'ws connection closed with exception %s' % ws.exception())

        self.request.app['websockets'].remove(ws)
        self.request.app['logger'].info('WS connection closed')

        return ws
    async def get(self, token: str) -> web.WebSocketResponse:
        """The function allows you to get information about all the friends of a given user.

        :param token: Token of current user.
        :type: str

        :return: JSON response with result information.
        :rtype: web.WebSocketResponse
        """
        ws = WSResponse()
        await ws.prepare(self.request)
        self.request.app['logger'].info("User connected in via WebScoket.")
        self.request.app['websockets'].append(ws)
        async for msg in ws:
            if msg.type != WSMsgType.ERROR:
                json_request = json.loads(str(msg.data, encoding='utf-8'))
                print(json_request)
                fields = json_request.get('fields', '')
                fields = ', '.join(fields)
                try:
                    self.request.app['logger'].info(
                        f"WSGetFriends.get called with params: \n"
                        f"target_id: {json_request['id']}, \n"
                        f"fields: {fields}.")
                    api = self.request.app['users'][token]

                    result = await api.get_friends(
                        target_id=json_request['id'], fields=fields)
                    result['self'] = await api.get_profileinfo() \
                        if json_request['id'] == 0 else await api.get_info(
                        user_ids=[json_request['id']],
                        fields=json_request['fields']
                    )
                    self.request.app['logger'].info(
                        f"WSGetFriends.get result status code {result['status']}."
                    )
                    await ws.send_json(result)
                except KeyError as e:
                    self.request.app['logger'].error(
                        f"WSGetFriends.get error: {str(e)}.")
                    await ws.send_json(
                        Response(status=ResponseStatus.SERVER_ERROR,
                                 reason=str(e),
                                 response_type=ResponseTypes.ERROR))

            else:
                self.request.app['logger'].info(
                    'ws connection closed with exception %s' % ws.exception())

        self.request.app['websockets'].remove(ws)
        self.request.app['logger'].info('WS connection closed')

        return ws
예제 #13
0
    async def get(self, token: str) -> web.Response:
        """The function allows you to take information about the users who liked the given post.

        :param token: Token of current user.
        :type: str

        :return: JSON response with result information.
        :rtype: web.Response
        """
        try:
            ids = parse.urlparse(self.request.query['ids'])
        except KeyError:
            self.request.app['logger'].error("URL parse error.")
            return web.json_response(
                Response(status=ResponseStatus.SERVER_ERROR,
                         reason="URL parse error.",
                         response_type=ResponseTypes.ERROR))
        api = self.request.app['users'][token]
        result = await api.get_info(user_ids=ids)
        self.request.app['logger'].info("HTTPGetLikedPeoples.get called.")

        return web.json_response(result)