lbry-sdk/lbrynet/dht/contact.py

59 lines
2 KiB
Python
Raw Normal View History

2015-08-20 17:27:15 +02:00
class Contact(object):
""" Encapsulation for remote contact
2016-12-14 00:08:29 +01:00
2015-08-20 17:27:15 +02:00
This class contains information on a single remote contact, and also
provides a direct RPC API to the remote node which it represents
"""
2017-03-31 19:32:43 +02:00
2015-08-20 17:27:15 +02:00
def __init__(self, id, ipAddress, udpPort, networkProtocol, firstComm=0):
self.id = id
self.address = ipAddress
self.port = udpPort
self._networkProtocol = networkProtocol
self.commTime = firstComm
2016-12-14 00:08:29 +01:00
2015-08-20 17:27:15 +02:00
def __eq__(self, other):
if isinstance(other, Contact):
return self.id == other.id
elif isinstance(other, str):
return self.id == other
else:
return False
2016-12-14 00:08:29 +01:00
2015-08-20 17:27:15 +02:00
def __ne__(self, other):
if isinstance(other, Contact):
return self.id != other.id
elif isinstance(other, str):
return self.id != other
else:
return True
def compact_ip(self):
2016-11-30 21:20:45 +01:00
compact_ip = reduce(
lambda buff, x: buff + bytearray([int(x)]), self.address.split('.'), bytearray())
2015-08-20 17:27:15 +02:00
return str(compact_ip)
2016-12-14 00:08:29 +01:00
2015-08-20 17:27:15 +02:00
def __str__(self):
2016-11-30 21:20:45 +01:00
return '<%s.%s object; IP address: %s, UDP port: %d>' % (
self.__module__, self.__class__.__name__, self.address, self.port)
2016-12-14 00:08:29 +01:00
2015-08-20 17:27:15 +02:00
def __getattr__(self, name):
""" This override allows the host node to call a method of the remote
node (i.e. this contact) as if it was a local function.
2016-12-14 00:08:29 +01:00
2015-08-20 17:27:15 +02:00
For instance, if C{remoteNode} is a instance of C{Contact}, the
following will result in C{remoteNode}'s C{test()} method to be
called with argument C{123}::
remoteNode.test(123)
2016-12-14 00:08:29 +01:00
2015-08-20 17:27:15 +02:00
Such a RPC method call will return a Deferred, which will callback
when the contact responds with the result (or an error occurs).
This happens via this contact's C{_networkProtocol} object (i.e. the
host Node's C{_protocol} object).
"""
2017-03-31 19:32:43 +02:00
2015-08-20 17:27:15 +02:00
def _sendRPC(*args, **kwargs):
return self._networkProtocol.sendRPC(self, name, args, **kwargs)
2017-03-31 19:32:43 +02:00
2015-08-20 17:27:15 +02:00
return _sendRPC