Skip to content

Commit 6ee6c0b

Browse files
authored
Merge pull request #2 from lighthouse-web3/v0.0.7
V0.0.7
2 parents 6fc2add + 930d1fa commit 6ee6c0b

File tree

15 files changed

+360
-98
lines changed

15 files changed

+360
-98
lines changed

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ lh = Lighthouse(token="your_token")
2727
```python
2828
from lighthouseweb3 import Lighthouse
2929
lh = Lighthouse()
30-
response = lh.deploy("path/to/file")
30+
response = lh.upload("path/to/file")
3131
print(response) # prints a dict containing the cid of the file
3232
```
3333

@@ -36,7 +36,7 @@ print(response) # prints a dict containing the cid of the file
3636
```python
3737
from lighthouseweb3 import Lighthouse
3838
lh = Lighthouse("my-lightouse-token")
39-
response = lh.deploy("path/to/directory")
39+
response = lh.upload("path/to/directory")
4040
print(response) # prints a dict containing the root cid of the directory
4141
```
4242

@@ -45,11 +45,11 @@ print(response) # prints a dict containing the root cid of the directory
4545
The tests are written with inheritance from the unittest module. To run the tests, run the following command:
4646

4747
```
48-
pip install requirements.txt && python -m unittest discover
48+
pip install -r requirements.txt && python -m unittest discover
4949
```
5050

5151
or using nose2
5252

5353
```
54-
pip install requirements.txt && python -m nose2
54+
pip install -r requirements.txt && python -m nose2
5555
```

setup.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44

55
setup(
66
name="lighthouseweb3",
7-
version="0.0.6",
7+
version="0.0.7",
88
license="GNU GENERAL PUBLIC LICENSE",
99
description="Lighthouse Python SDK",
10-
author="Perfection Loveday",
11-
author_email="perfection@lighthouse.storage",
10+
author="Ayobami Oki| Ravish Sharma | Perfection Loveday",
11+
author_email="ravish@lighthouse.storage",
1212
url="https://github.com/lighthouse-web3/lighthouse-python-sdk",
1313
packages=find_packages("src"),
1414
package_dir={"": "src"},

src/lighthouseweb3/__init__.py

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#!/usr/bin/env python3
22

33
import os
4-
from .functions import deploy as d
5-
from .functions import types as t
4+
import io
5+
from typing import List
6+
from .functions import upload as d, types as t, deal_status, get_uploads as getUploads
67

78

89
class Lighthouse:
@@ -13,12 +14,55 @@ def __init__(self, token: str = ""):
1314
"No token provided: Please provide a token or set the LIGHTHOUSE_TOKEN environment variable"
1415
)
1516

16-
def deploy(self, source: str) -> t.Deploy:
17+
def upload(self, source: str) -> t.Upload:
1718
"""
18-
Deploy a file or directory to the lighthouse network
19-
@params {source}: str, path to file or directory
19+
Upload a file or directory to the Lighthouse.
20+
21+
:param source: str, path to file or directory
22+
:return: t.Upload, the upload result
23+
"""
24+
try:
25+
return d.upload(source, self.token)
26+
except Exception as e:
27+
raise e
28+
29+
def uploadBlob(self, source: io.BufferedReader, filename: str) -> t.Upload:
30+
"""
31+
Upload Blob a file or directory to the Lighthouse.
32+
33+
:param source: str, path to file or directory
34+
:return: t.Upload, the upload result
35+
"""
36+
if not (hasattr(source, 'read') and hasattr(source, 'close')):
37+
raise TypeError("source must have 'read' and 'close' methods")
38+
try:
39+
return d.uploadBlob(source, filename, self.token)
40+
except Exception as e:
41+
raise e
42+
43+
@staticmethod
44+
def getDealStatus(cid: str) -> List[t.DealData]:
45+
"""
46+
Get deal status from the Lighthouse.
47+
48+
:param cid: str, content identifier
49+
:return: List[t.DealData], list of deal data
50+
"""
51+
try:
52+
return deal_status.get_deal_status(cid)
53+
except Exception as e:
54+
raise e
55+
56+
@staticmethod
57+
def getUploads(publicKey: str, pageNo: int = 1) -> List[t.DealData]:
58+
"""
59+
Get uploads from the Lighthouse.
60+
61+
:param publicKey: str, public key
62+
:param pageNo: int, page number (default: 1)
63+
:return: List[t.DealData], list of deal data
2064
"""
2165
try:
22-
return d.deploy(source, self.token)
66+
return getUploads.get_uploads(publicKey, pageNo)
2367
except Exception as e:
2468
raise e

src/lighthouseweb3/functions/axios.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,28 @@ def post_files(
5959
except Exception as e:
6060
utils.close_files_after_upload(files)
6161
raise e
62+
63+
def post_blob(
64+
self, file: BufferedReader, filename: str, headers: Dict[str, str] = None, **kwargs
65+
) -> dict | Exception:
66+
try:
67+
self.parse_url_query(kwargs.get("query", None))
68+
files = [(
69+
"file",
70+
(
71+
utils.extract_file_name(filename),
72+
file.read(),
73+
"application/octet-stream",
74+
),
75+
),]
76+
r = req.post(self.url, headers=headers, files=files)
77+
r.raise_for_status()
78+
file.close()
79+
try:
80+
return r.json()
81+
except Exception:
82+
temp = r.text.split("\n")
83+
return json.loads(temp[len(temp) - 2])
84+
except Exception as e:
85+
file.close()
86+
raise e

src/lighthouseweb3/functions/config.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
class Config:
55
"""Config class for lighthouse"""
66

7-
lighthouse_api = "http://13.234.35.183:5050" # "https://api.lighthouse.storage"
7+
# lighthouse_api = "http://13.234.35.183:5050" # "https://api.lighthouse.storage"
8+
lighthouse_api = 'https://api.lighthouse.storage'
89
lighthouse_node = "https://node.lighthouse.storage"
910
lighthouse_bls_node = "https://encryption.lighthouse.storage"
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import requests
2+
from typing import List
3+
from .config import Config
4+
from . import types as t
5+
6+
7+
def get_deal_status(cid: str) -> List[t.DealData]:
8+
try:
9+
url = f"{Config.lighthouse_api}/api/lighthouse/deal_status?cid={cid}"
10+
response = requests.get(url)
11+
response.raise_for_status()
12+
return response.json()
13+
except requests.HTTPError as error:
14+
raise Exception(error.response.text)

src/lighthouseweb3/functions/deploy.py

Lines changed: 0 additions & 43 deletions
This file was deleted.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import requests
2+
from .config import Config
3+
from . import types as t
4+
5+
6+
def bytes_to_size(bytes_size):
7+
units = ['B', 'KB', 'MB', 'GB', 'TB']
8+
index = 0
9+
while bytes_size >= 1024 and index < len(units) - 1:
10+
bytes_size /= 1024
11+
index += 1
12+
return f"{round(bytes_size, 2)} {units[index]}"
13+
14+
15+
def get_uploads(publicKey: str, pageNo: int = 1) -> t.UploadsResponseType:
16+
try:
17+
url = f"{Config.lighthouse_api}/api/user/files_uploaded?publicKey={publicKey}&pageNo={pageNo}"
18+
response = requests.get(url)
19+
response.raise_for_status()
20+
return response.json()
21+
except requests.HTTPError as error:
22+
raise Exception(error.response.text)

src/lighthouseweb3/functions/types.py

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
#!/usr/bin/env python3
22

3+
from typing import List, Dict, Tuple, NewType, TypedDict
34
from dataclasses import dataclass
4-
from typing import Dict, NewType, List, Tuple, TypedDict
55

66

77
@dataclass
8-
class Deploy(TypedDict):
9-
"""typings for deploy function"""
8+
class Upload(TypedDict):
9+
"""typings for upload function"""
1010

1111
data: dict | str
1212

@@ -17,3 +17,39 @@ class FileDict(TypedDict):
1717
files: List[str]
1818
is_dir: bool
1919
path: str
20+
21+
22+
class DealData(TypedDict):
23+
"""typings for deal Status"""
24+
chainDealID: str
25+
endEpoch: str
26+
publishCID: str
27+
storageProvider: str
28+
dealStatus: str
29+
bundleId: str
30+
dealUUID: str
31+
startEpoch: str
32+
providerCollateral: str
33+
lastUpdate: int
34+
dealId: int
35+
miner: str
36+
content: int
37+
38+
39+
class FileObject(TypedDict):
40+
publicKey: str
41+
fileName: str
42+
mimeType: str
43+
txHash: str
44+
status: str
45+
createdAt: int
46+
fileSizeInBytes: str
47+
cid: str
48+
id: str
49+
lastUpdate: int
50+
encryption: bool
51+
52+
53+
class UploadsResponseType(TypedDict):
54+
fileList: List[FileObject]
55+
totalFiles: int
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#!/usr/bin/env python3
2+
3+
from io import BufferedReader
4+
from typing import Dict, List, Tuple
5+
from .axios import Axios
6+
from .utils import is_dir, walk_dir_tree, extract_file_name, NamedBufferedReader
7+
from .config import Config
8+
from . import types as t
9+
10+
11+
def upload(source: str | BufferedReader | NamedBufferedReader, token: str) -> t.Upload:
12+
"""
13+
Deploy a file or directory to the lighthouse network
14+
@params {source}: str, path to file or directory
15+
@params {token}: str, lighthouse api token
16+
"""
17+
# create headers
18+
headers = {
19+
"Authorization": f"Bearer {token}",
20+
# "Content-Type": "multipart/form-data",
21+
"Encryption": "false",
22+
"Mime-Type": "application/octet-stream",
23+
}
24+
try:
25+
# create http object
26+
axios = Axios(Config.lighthouse_node + "/api/v0/add")
27+
# create list of files to upload
28+
29+
if (isinstance(source, str)):
30+
file_dict: t.FileDict = {}
31+
32+
# check if source is a directory
33+
if is_dir(source):
34+
# walk directory tree and add files to list
35+
file_dict["files"], root = walk_dir_tree(source)
36+
file_dict["is_dir"] = True
37+
file_dict["path"] = root
38+
else:
39+
# add file to list
40+
file_dict["files"] = [source]
41+
file_dict["is_dir"] = False
42+
file_dict["path"] = source
43+
return {"data": axios.post_files(file_dict, headers)}
44+
else:
45+
return {"data": axios.post_blob(source, source.name, headers)}
46+
except Exception as e:
47+
print(e)
48+
raise e
49+
50+
51+
def uploadBlob(source: BufferedReader, filename: str, token: str) -> t.Upload:
52+
"""
53+
Upload a Buffer or readable Object
54+
@params {source}: str, path to file or directory
55+
@params {token}: str, lighthouse api token
56+
"""
57+
# create headers
58+
headers = {
59+
"Authorization": f"Bearer {token}",
60+
# "Content-Type": "multipart/form-data",
61+
"Encryption": "false",
62+
"Mime-Type": "application/octet-stream",
63+
}
64+
try:
65+
# create http object
66+
axios = Axios(Config.lighthouse_node + "/api/v0/add")
67+
# create list of files to upload
68+
return {"data": axios.post_blob(source, filename, headers)}
69+
except Exception as e:
70+
print(e)
71+
raise e

0 commit comments

Comments
 (0)