Skip to content

Commit

Permalink
Update and modify files for the project
Browse files Browse the repository at this point in the history
- Updated files:
  - src/bee_py/bee.py
  - src/bee_py/types/type.py
  - src/bee_py/utils/data.py
  - src/bee_py/utils/file.py
  - src/bee_py/utils/hex.py
  - src/bee_py/utils/type.py
  • Loading branch information
Aviksaikat committed Dec 5, 2023
1 parent 33fef63 commit 6139e38
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 35 deletions.
47 changes: 27 additions & 20 deletions src/bee_py/bee.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Optional
from typing import Optional, Union

from ape.types import AddressType
from swarm_cid import ReferenceType
Expand All @@ -10,7 +10,7 @@
from bee_py.feed.retrievable import get_all_sequence_update_references
from bee_py.feed.topic import make_topic, make_topic_from_string
from bee_py.feed.type import is_feed_type
from bee_py.modules.bytes import *
from bee_py.modules import bytes as bytes_api
from bee_py.modules.bzz import *
from bee_py.modules.chunk import *
from bee_py.modules.feed import create_feed_manifest
Expand Down Expand Up @@ -56,27 +56,15 @@
from bee_py.utils.bytes import wrap_bytes_with_helpers
from bee_py.utils.collection import assert_collection, make_collection_from_file_list
from bee_py.utils.collection_node import make_collection_from_fs
from bee_py.utils.data import prepare_web_socket_data
from bee_py.utils.data import prepare_websocket_data
from bee_py.utils.error import BeeArgumentError, BeeError
from bee_py.utils.eth import make_eth_address, make_hex_eth_address
from bee_py.utils.file import is_file
from bee_py.utils.type import (
addCidConversionFunction,
assertAddressPrefix,
assertAllTagsOptions,
assertBatchId,
assertCollectionUploadOptions,
assertData,
assertFileData,
assertFileUploadOptions,
assertPssMessageHandler,
assertPublicKey,
assertReference,
assertReferenceOrEns,
assertRequestOptions,
assertUploadOptions,
add_cid_conversion_function,
assert_reference,
assert_reference_or_ens,
make_reference_or_ens,
make_tag_uid,
makeReferenceOrEns,
)
from bee_py.utils.urls import assert_bee_url, strip_last_slash

Expand All @@ -94,7 +82,14 @@ class Bee:
request_options: Ky instance that defines connection to Bee node.
"""

def __init__(self, url: str, options: Optional[dict] = None):
# URL on which is the main API of Bee node exposed
url: str
# Default Signer object used for signing operations, mainly Feeds
signer: Optional[Signer]
# Ky instance that defines connection to Bee node
request_options: BeeRequestOptions

def __init__(self, url: str, options: Optional[BeeOptions] = None):
"""
Constructs a new Bee instance.
Expand All @@ -120,5 +115,17 @@ def __init__(self, url: str, options: Optional[dict] = None):
"adapter": options.get("adapter", None),
}

def upload_data(
self,
postage_batch_id: Union[str, BatchId],
data: Union[str, bytes],
options: Optional[UploadOptions] = None,
request_options: Optional[BeeRequestOptions] = None,
):
# if options:
# assert_upload_options(options)
# return bytes_api.upload(request_options, data, postage_batch_id, options)
...

def download_chunk(self):
...
27 changes: 15 additions & 12 deletions src/bee_py/types/type.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ class PssMessageHandler(BaseModel):


class BeeOptions(BeeRequestOptions):
signer: Optional[Union[str, bytes, object]] = None
signer: Optional[Union[str, bytes]] = None


class BrandedType(Generic[Type, Name]):
Expand Down Expand Up @@ -551,6 +551,9 @@ class TransactionOptions(BaseModel):
gas_limit: str = Field(..., alias="gasLimit")


CashoutOptions = TransactionOptions


class GetStake(BaseModel):
staked_amount: str = Field(..., alias="stakedAmount")

Expand Down Expand Up @@ -849,6 +852,17 @@ class Config:
arbitrary_types_allowed = True


class UploadResultWithCid(UploadResult):
"""
Function that converts the reference into Swarm CIDs
@throws TypeError if the reference is encrypted reference (eq. 128 chars long) which is not supported in CID
@see https://github.com/aviksaikat/swarm-cid-py
"""

cid: callable[[], str]


class UploadOptions(BaseModel):
pin: Optional[bool] = False
encrypt: Optional[bool] = False
Expand Down Expand Up @@ -932,17 +946,6 @@ class SOCWriter(SOCReader):
upload: callable[[Union(str, BatchId), bytes, bytes, UploadOptions], Reference]


class UploadResultWithCid(UploadResult):
"""
UploadResultWithCid model.
Attributes:
cid: A function that converts the reference into Swarm CIDs.
"""

cid: callable[[], str]


class AllTagsOptions(BaseModel):
limit: Optional[int] = None
offest: Optional[int] = None
Expand Down
19 changes: 17 additions & 2 deletions src/bee_py/utils/data.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
def prepare_web_socket_data():
...
import io
from typing import Union


def prepare_websocket_data(data: Union[str, bytes, bytearray, memoryview]) -> bytes:
if isinstance(data, str):
return data.encode()

if isinstance(data, (bytes, bytearray, memoryview)):
return bytes(data)

if isinstance(data, io.IOBase):
# Read the data from the file-like object
return data.read()

msg = "Unknown websocket data type"
raise TypeError(msg)
Empty file removed src/bee_py/utils/file.py
Empty file.
8 changes: 8 additions & 0 deletions src/bee_py/utils/hex.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,11 @@ def remove_0x_prefix(input_string: str) -> str:
return input_string[2:]
else:
return input_string


def assert_hex_string(value: bytes, length: Optional[int] = None) -> Optional[bool]:
if len(value) != length:
return False
if not is_hex_string(value):
msg = f"{value} is not a valid hex string"
raise TypeError(msg)
108 changes: 107 additions & 1 deletion src/bee_py/utils/type.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,38 @@
from typing import Union

from bee_py.types.type import Tag
from ens.utils import is_valid_ens_name
from swarm_cid import ReferenceType, decodeCid, encodeReference

from bee_py.types.type import (
ADDRESS_HEX_LENGTH,
BATCH_ID_HEX_LENGTH,
ENCRYPTED_REFERENCE_HEX_LENGTH,
PSS_TARGET_HEX_LENGTH_MAX,
PUBKEY_HEX_LENGTH,
REFERENCE_HEX_LENGTH,
TAGS_LIMIT_MAX,
TAGS_LIMIT_MIN,
AddressPrefix,
AllTagsOptions,
BatchId,
BeeRequestOptions,
CashoutOptions,
CollectionUploadOptions,
FileUploadOptions,
NumberString,
PostageBatchOptions,
PssMessageHandler,
Reference,
ReferenceOrENS,
Tag,
TransactionHash,
TransactionOptions,
UploadOptions,
UploadResult,
UploadResultWithCid,
)
from bee_py.utils.error import BeeArgumentError, BeeError
from bee_py.utils.hex import assert_hex_string, is_hex_string, is_prefixed_hex_string


def assert_non_negative_integer(value: Union[int, str], name: str = "Value"):
Expand Down Expand Up @@ -57,3 +89,77 @@ def make_tag_uid(tag_uid: Union[int, str, None]) -> int:
raise TypeError(msg) # noqa: B904
msg = "tagUid has to be either Tag or a number (UID)!"
raise TypeError(msg)


def assert_reference(value: any) -> None:
try:
assert_hex_string(value, REFERENCE_HEX_LENGTH)
except TypeError:
assert_hex_string(value, ENCRYPTED_REFERENCE_HEX_LENGTH)


def assert_reference_or_ens(value: any) -> ReferenceOrENS:
if not isinstance(value, str):
msg = "ReferenceOrEns has to be a string!"
raise TypeError(msg)

if is_hex_string(value):
assert_reference(value)
return

if not is_valid_ens_name(value):
msg = "ReferenceOrEns is not valid Reference, but also not valid ENS domain."
raise TypeError(msg)


def make_reference_or_ens(value: any, expected_cid_type: ReferenceType) -> ReferenceOrENS:
"""
Converts a Swarm CID or ENS name to a hex-encoded Swarm Reference.
Args:
value (str): The Swarm CID or ENS name.
expected_cid_type (str): The expected type of the Swarm CID.
Returns:
str: The hex-encoded Swarm Reference.
"""
if not isinstance(value, str):
msg = "ReferenceCidOrEns has to be a string!"
raise TypeError(msg)

try:
result = decodeCid(value)

if result.type != expected_cid_type:
msg = f'CID was expected to be of type {expected_cid_type}, but got instead {result.type if result.type else "non-Swarm CID"}' # noqa: E501
raise BeeError(msg)

return result.reference
except BeeError as e:
raise e

assert_reference_or_ens(value)

return value


def add_cid_conversion_function(result: UploadResult, cid_type: ReferenceType) -> UploadResultWithCid:
"""
Adds a getter method to the result object that converts the reference to a CID base32 encoded string.
Args:
result (UploadResult): The object to add the getter method to.
cid_type (ReferenceType): The type of the CID.
Returns:
UploadResultWithCid
"""

def cid():
return encodeReference(result.reference, cid_type)

return UploadResultWithCid(cid=cid)


def assert_upload_options():
...

0 comments on commit 6139e38

Please sign in to comment.