lbry-sdk/lbrynet/core/Offer.py

63 lines
1.7 KiB
Python
Raw Normal View History

from decimal import Decimal
class Offer(object):
2016-10-13 19:35:55 +02:00
"""A rate offer to download blobs from a host."""
2016-09-30 06:12:17 +02:00
RATE_ACCEPTED = "RATE_ACCEPTED"
RATE_TOO_LOW = "RATE_TOO_LOW"
RATE_UNSET = "RATE_UNSET"
def __init__(self, offer):
self._state = None
self.rate = None
if isinstance(offer, Decimal):
self.rate = round(offer, 5)
elif isinstance(offer, float):
self.rate = round(Decimal(offer), 5)
if self.rate is None or self.rate < Decimal(0.0):
2016-10-03 08:44:58 +02:00
self.unset()
@property
2016-10-13 19:35:55 +02:00
def is_accepted(self):
2016-09-30 06:12:17 +02:00
return self._state is Offer.RATE_ACCEPTED
@property
2016-10-13 19:35:55 +02:00
def is_too_low(self):
2016-09-30 06:12:17 +02:00
return self._state is Offer.RATE_TOO_LOW
2016-10-03 08:44:58 +02:00
@property
def is_unset(self):
return self._state is Offer.RATE_UNSET
@property
def message(self):
2016-10-13 19:35:55 +02:00
if self.is_accepted:
2016-09-30 06:12:17 +02:00
return Offer.RATE_ACCEPTED
2016-10-13 19:35:55 +02:00
elif self.is_too_low:
2016-09-30 06:12:17 +02:00
return Offer.RATE_TOO_LOW
2016-10-03 08:44:58 +02:00
elif self.is_unset:
2016-09-30 06:12:17 +02:00
return Offer.RATE_UNSET
2016-10-03 08:44:58 +02:00
return None
def accept(self):
if self.is_unset or self._state is None:
2016-09-30 06:12:17 +02:00
self._state = Offer.RATE_ACCEPTED
def reject(self):
if self.is_unset or self._state is None:
2016-09-30 06:12:17 +02:00
self._state = Offer.RATE_TOO_LOW
2016-10-03 08:44:58 +02:00
def unset(self):
self._state = Offer.RATE_UNSET
def handle(self, reply_message):
if reply_message == Offer.RATE_TOO_LOW:
self.reject()
elif reply_message == Offer.RATE_ACCEPTED:
self.accept()
elif reply_message == Offer.RATE_UNSET:
self.unset()
else:
raise Exception("Unknown offer reply %s" % str(reply_message))