Ejemplo n.º 1
0
def unpack_legacy_message(headers, message):
    '''Unpack legacy pubsub messages for VIP agents.

    Loads JSON-formatted message parts and removes single-frame messages
    from their containing list. Does not alter headers.
    '''
    if not isinstance(headers, Headers):
        headers = Headers(headers)
    try:
        content_type = headers['Content-Type']
    except KeyError:
        return headers, message
    if isinstance(content_type, str):
        if content_type.lower() == 'application/json':
            if isinstance(message, list) and len(message) == 1:
                return jsonapi.loads(message[0])
            if isinstance(message, str):
                return jsonapi.loads(message)
        if isinstance(message, list) and len(message) == 1:
            return message[0]
    if isinstance(content_type, list) and isinstance(message, list):
        parts = [(jsonapi.loads(msg)
                  if str(ctype).lower() == 'application/json' else msg)
                 for ctype, msg in zip(content_type, message)]
        parts.extend(message[len(parts):])
        if len(parts) == len(content_type) == 1:
            return parts[0]
        return parts
    return message
Ejemplo n.º 2
0
 def forward(self, peer, sender, bus, topic, headers, message):
     headers = Headers(headers)
     headers['VIP.peer'] = encode_peer(peer)
     headers['VIP.sender'] = encode_peer(sender)
     headers['VIP.bus'] = bus
     parts = [topic]
     if message is not None:
         if 'Content-Type' in headers:
             if isinstance(message, list):
                 parts.extend(message)
             else:
                 parts.append(message)
         else:
             parts.append(jsonapi.dumps(message))
             headers['Content-Type'] = 'application/json'
     parts.insert(1, jsonapi.dumps(headers.dict))
     self.out_sock.send_multipart(parts)