Ejemplo n.º 1
0
    def _pb_request(self, endpoint, request_pb, response_pb):
        """Send a Protocol Buffer formatted chat API request.

        Args:
            endpoint (str): The chat API endpoint to use.
            request_pb: The request body as a Protocol Buffer message.
            response_pb: The response body as a Protocol Buffer message.

        Raises:
            NetworkError: If the request fails.
        """
        logger.debug('Sending Protocol Buffer request %s:\n%s', endpoint,
                     request_pb)
        res = yield from self._base_request(
            'https://clients6.google.com/chat/v1/{}'.format(endpoint),
            'application/json+protobuf',  # The request body is pblite.
            'protojson',  # The response should be pblite.
            json.dumps(pblite.encode(request_pb))
        )
        pblite.decode(response_pb, javascript.loads(res.body.decode()),
                      ignore_first_item=True)
        logger.debug('Received Protocol Buffer response:\n%s', response_pb)
        status = response_pb.response_header.status
        if status != hangouts_pb2.RESPONSE_STATUS_OK:
            description = response_pb.response_header.error_description
            raise exceptions.NetworkError(
                'Request failed with status {}: \'{}\''
                .format(status, description)
            )
Ejemplo n.º 2
0
def test_decode():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        1,
        [3, 4],
        'foo',
        ['bar', 'baz'],
        1,
        [2, 3],
        [1],
        [[2], [3]],
        'AA==',
        ['AAE=', 'AAEC'],
    ])
    assert message == test_pblite_pb2.TestMessage(
        test_int=1,
        test_repeated_int=[3, 4],
        test_string='foo',
        test_repeated_string=['bar', 'baz'],
        test_enum=test_pblite_pb2.TestMessage.TEST_1,
        test_repeated_enum=[
            test_pblite_pb2.TestMessage.TEST_2,
            test_pblite_pb2.TestMessage.TEST_3
        ],
        test_embedded_message=test_pblite_pb2.TestMessage.EmbeddedMessage(
            test_embedded_int=1, ),
        test_repeated_embedded_message=[
            test_pblite_pb2.TestMessage.EmbeddedMessage(test_embedded_int=2, ),
            test_pblite_pb2.TestMessage.EmbeddedMessage(test_embedded_int=3, ),
        ],
        test_bytes=b'\x00',
        test_repeated_bytes=[b'\x00\x01', b'\x00\x01\x02'],
    )
Ejemplo n.º 3
0
def test_decode_repeated_scalar_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        [1, 'foo', 2]
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 4
0
    def _pb_request(self, endpoint, request_pb, response_pb):
        """Send a Protocol Buffer formatted chat API request.

        Args:
            endpoint (str): The chat API endpoint to use.
            request_pb: The request body as a Protocol Buffer message.
            response_pb: The response body as a Protocol Buffer message.

        Raises:
            NetworkError: If the request fails.
        """
        logger.debug('Sending Protocol Buffer request %s:\n%s', endpoint,
                     request_pb)
        res = yield from self._base_request(
            'https://clients6.google.com/chat/v1/{}'.format(endpoint),
            'application/json+protobuf',  # The request body is pblite.
            'protojson',  # The response should be pblite.
            json.dumps(pblite.encode(request_pb))
        )
        pblite.decode(response_pb, javascript.loads(res.body.decode()),
                      ignore_first_item=True)
        logger.debug('Received Protocol Buffer response:\n%s', response_pb)
        status = response_pb.response_header.status
        if status != hangouts_pb2.RESPONSE_STATUS_OK:
            description = response_pb.response_header.error_description
            raise exceptions.NetworkError(
                'Request failed with status {}: \'{}\''
                .format(status, description)
            )
Ejemplo n.º 5
0
 def _on_receive_array(self, array):
     """Parse channel array and call the appropriate events."""
     if array[0] == 'noop':
         pass  # This is just a keep-alive, ignore it.
     else:
         wrapper = json.loads(array[0]['p'])
         # Wrapper appears to be a Protocol Buffer message, but encoded via
         # field numbers as dictionary keys. Since we don't have a parser
         # for that, parse it ad-hoc here.
         if '3' in wrapper:
             # This is a new client_id.
             self._client_id = wrapper['3']['2']
             logger.info('Received new client_id: %r', self._client_id)
             # Once client_id is received, the channel is ready to have
             # services added.
             yield from self._add_channel_services()
         if '2' in wrapper:
             pblite_message = json.loads(wrapper['2']['2'])
             if pblite_message[0] == 'cbu':
                 # This is a (Client)BatchUpdate containing StateUpdate
                 # messages.
                 batch_update = hangouts_pb2.BatchUpdate()
                 pblite.decode(batch_update, pblite_message,
                               ignore_first_item=True)
                 for state_update in batch_update.state_update:
                     logger.debug('Received StateUpdate:\n%s', state_update)
                     header = state_update.state_update_header
                     self._active_client_state = header.active_client_state
                     yield from self.on_state_update.fire(state_update)
             else:
                 logger.info('Ignoring message: %r', pblite_message[0])
Ejemplo n.º 6
0
 def _on_receive_array(self, array):
     """Parse channel array and call the appropriate events."""
     if array[0] == 'noop':
         pass  # This is just a keep-alive, ignore it.
     else:
         wrapper = json.loads(array[0]['p'])
         # Wrapper appears to be a Protocol Buffer message, but encoded via
         # field numbers as dictionary keys. Since we don't have a parser
         # for that, parse it ad-hoc here.
         if '3' in wrapper:
             # This is a new client_id.
             self._client_id = wrapper['3']['2']
             logger.info('Received new client_id: %r', self._client_id)
             # Once client_id is received, the channel is ready to have
             # services added.
             yield from self._add_channel_services()
         if '2' in wrapper:
             pblite_message = json.loads(wrapper['2']['2'])
             if pblite_message[0] == 'cbu':
                 # This is a (Client)BatchUpdate containing StateUpdate
                 # messages.
                 batch_update = hangouts_pb2.BatchUpdate()
                 pblite.decode(batch_update, pblite_message,
                               ignore_first_item=True)
                 for state_update in batch_update.state_update:
                     logger.debug('Received StateUpdate:\n%s', state_update)
                     header = state_update.state_update_header
                     self._active_client_state = header.active_client_state
                     yield from self.on_state_update.fire(state_update)
             else:
                 logger.info('Ignoring message: %r', pblite_message[0])
Ejemplo n.º 7
0
def test_decode_unserialized_fields():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        'foo',
    ])
    assert message == test_pblite_pb2.TestMessage(test_string='foo', )
Ejemplo n.º 8
0
def test_decode_unknown_enum():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        99,
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 9
0
def test_decode_unknown_enum():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        99,
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 10
0
def test_decode_unserialized_fields():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        'foo',
    ])
    assert message == test_pblite_pb2.TestMessage(
        test_string='foo',
    )
Ejemplo n.º 11
0
    def sendchatmessage(
            self, conversation_id, segments, image_id=None,
            otr_status=hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD,
            delivery_medium=None):
        """Send a chat message to a conversation.

        conversation_id must be a valid conversation ID. segments must be a
        list of message segments to send, in pblite format.

        otr_status determines whether the message will be saved in the server's
        chat history. Note that the OTR status of the conversation is
        irrelevant, clients may send messages with whatever OTR status they
        like.

        image_id is an option ID of an image retrieved from
        Client.upload_image. If provided, the image will be attached to the
        message.

        Raises hangups.NetworkError if the request fails.
        """
        segments_pb = []
        for segment_pblite in segments:
            segment_pb = hangouts_pb2.Segment()
            pblite.decode(segment_pb, segment_pblite)
            segments_pb.append(segment_pb)
        if delivery_medium is None:
            delivery_medium = hangouts_pb2.DeliveryMedium(
                medium_type=hangouts_pb2.DELIVERY_MEDIUM_BABEL,
            )

        request = hangouts_pb2.SendChatMessageRequest(
            request_header=self._get_request_header_pb(),
            message_content=hangouts_pb2.MessageContent(
                segment=segments_pb,
            ),
            event_request_header=hangouts_pb2.EventRequestHeader(
                conversation_id=hangouts_pb2.ConversationId(
                    id=conversation_id,
                ),
                client_generated_id=self.get_client_generated_id(),
                expected_otr=otr_status,
                delivery_medium=delivery_medium,
                event_type=hangouts_pb2.EVENT_TYPE_REGULAR_CHAT_MESSAGE,
            ),
        )

        if image_id is not None:
            request.existing_media = hangouts_pb2.ExistingMedia(
                photo=hangouts_pb2.Photo(photo_id=image_id)
            )

        response = hangouts_pb2.SendChatMessageResponse()
        yield from self._pb_request('conversations/sendchatmessage', request,
                                    response)
        return response
Ejemplo n.º 12
0
def test_decode_ignore_first_item():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        'ignored',
        1,
        [3, 4],
    ], ignore_first_item=True)
    assert message == test_pblite_pb2.TestMessage(
        test_int=1,
        test_repeated_int=[3, 4],
    )
Ejemplo n.º 13
0
def test_decode_ignore_first_item():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        'ignored',
        1,
        [3, 4],
    ], ignore_first_item=True)
    assert message == test_pblite_pb2.TestMessage(
        test_int=1,
        test_repeated_int=[3, 4],
    )
Ejemplo n.º 14
0
def test_decode_message_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        None,
        None,
        1,
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 15
0
def test_decode_message_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        None,
        None,
        1,
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 16
0
def test_decode_dict():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        1,
        {
            '7': [2],
        },
    ])
    assert message == test_pblite_pb2.TestMessage(
        test_int=1,
        test_embedded_message=test_pblite_pb2.TestMessage.EmbeddedMessage(
            test_embedded_int=2, ),
    )
Ejemplo n.º 17
0
def test_decode_dict():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        1,
        {
            '7': [2],
        },
    ])
    assert message == test_pblite_pb2.TestMessage(
        test_int=1,
        test_embedded_message=test_pblite_pb2.TestMessage.EmbeddedMessage(
            test_embedded_int=2,
        ),
    )
Ejemplo n.º 18
0
def test_decode_bytes_invalid_value():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        'A?==',
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 19
0
def test_decode_repeated_bytes_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        [1],
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 20
0
def test_decode_repeated_message_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        [1],
    ])
    assert message == test_pblite_pb2.TestMessage(
        test_repeated_embedded_message=[
            test_pblite_pb2.TestMessage.EmbeddedMessage(),
        ], )
Ejemplo n.º 21
0
def test_decode_repeated_message_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        [1],
    ])
    assert message == test_pblite_pb2.TestMessage(
        test_repeated_embedded_message=[
            test_pblite_pb2.TestMessage.EmbeddedMessage(),
        ],
    )
Ejemplo n.º 22
0
def test_decode():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        1,
        [3, 4],
        'foo',
        ['bar', 'baz'],
        1,
        [2, 3],
        [1],
        [[2], [3]],
        'AA==',
        ['AAE=', 'AAEC'],
    ])
    assert message == test_pblite_pb2.TestMessage(
        test_int=1,
        test_repeated_int=[3, 4],
        test_string='foo',
        test_repeated_string=['bar', 'baz'],
        test_enum=test_pblite_pb2.TestMessage.TEST_1,
        test_repeated_enum=[test_pblite_pb2.TestMessage.TEST_2,
                            test_pblite_pb2.TestMessage.TEST_3],
        test_embedded_message=test_pblite_pb2.TestMessage.EmbeddedMessage(
            test_embedded_int=1,
        ),
        test_repeated_embedded_message=[
            test_pblite_pb2.TestMessage.EmbeddedMessage(
                test_embedded_int=2,
            ),
            test_pblite_pb2.TestMessage.EmbeddedMessage(
                test_embedded_int=3,
            ),
        ],
        test_bytes=b'\x00',
        test_repeated_bytes=[b'\x00\x01', b'\x00\x01\x02'],
    )
Ejemplo n.º 23
0
def test_decode_unknown_field():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [None] * 99 + [1])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 24
0
def test_decode_scalar_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        'foo',
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 25
0
def test_decode_repeated_scalar_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [None, [1, 'foo', 2]])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 26
0
def test_decode_scalar_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        'foo',
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 27
0
def test_decode_unknown_field():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [None] * 99 + [1])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 28
0
def test_decode_repeated_bytes_wrong_type():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None, None, None, None, None, None, None, None, None, [1],
    ])
    assert message == test_pblite_pb2.TestMessage()
Ejemplo n.º 29
0
def test_decode_repeated_bytes_invalid_value():
    message = test_pblite_pb2.TestMessage()
    pblite.decode(message, [
        None, None, None, None, None, None, None, None, None, ['A?=='],
    ])
    assert message == test_pblite_pb2.TestMessage()