|
| 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