depot/packages/servers/reflex-cache/reflex_cache/ipfs.py

31 lines
1 KiB
Python
Raw Permalink Normal View History

2022-02-26 01:48:16 +02:00
from urllib.parse import quote_plus
import requests
import requests_unixsocket
class IPFSController:
def __init__(self, apiAddress, nixCache, db):
self.__addr = f'http+unix://{quote_plus(apiAddress.get("unix"))}'
self.__nix = nixCache
self.__db = db
def ipfs_fetch_task(self, nar):
print(f"Downloading NAR: {nar}")
2022-03-02 00:59:31 +02:00
code, content = self.__nix.try_all("get", nar)
2022-02-26 01:48:16 +02:00
if code == 200:
2022-03-02 00:59:31 +02:00
upload = {"file": ("FILE", content, "application/octet-stream")}
2022-02-26 01:48:16 +02:00
try:
2022-03-02 00:59:31 +02:00
rIpfs = requests_unixsocket.post(
f"{self.__addr}/api/v0/add?pin=false&quieter=true", files=upload
)
2022-02-26 01:48:16 +02:00
hash = rIpfs.json()["Hash"]
print(f"Mapped: {nar} -> /ipfs/{hash}")
self.__db.set_path(nar, hash)
return (nar, 200, hash)
except requests.ConnectionError as e:
print(e)
return (nar, 502, False)
else:
return (nar, code, False)