mirror of
https://github.com/NohamR/GoFileCLI.git
synced 2025-05-24 14:22:04 +00:00
Compare commits
No commits in common. "main" and "1.0.0" have entirely different histories.
@ -1,3 +1,2 @@
|
||||
TOKEN = ""
|
||||
PRIVATE_PARENT_ID = ""
|
||||
GOPLOAD_ACCOUNT_ID = ""
|
86
.github/workflows/release.yml
vendored
86
.github/workflows/release.yml
vendored
@ -27,7 +27,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Check-out repository
|
||||
uses: actions/checkout@v1
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
@ -41,25 +41,30 @@ jobs:
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
pip install -r requirements.txt
|
||||
pip install nuitka
|
||||
|
||||
- name: Build Executable with Nuitka
|
||||
run: |
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist gofilecli.py --include-data-files=./assets/sounds/Blow_edited.wav=assets/sounds/Blow_edited.wav
|
||||
uses: Nuitka/Nuitka-Action@main
|
||||
with:
|
||||
nuitka-version: main
|
||||
script-name: gofilecli.py
|
||||
onefile: true
|
||||
|
||||
- name: Upload Artifact[win-x64]
|
||||
uses: actions/upload-artifact@v3.1.3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: GoFileCLI_win-x64
|
||||
path: |
|
||||
dist/gofilecli.exe
|
||||
build/gofilecli.exe
|
||||
|
||||
build-linux-x64:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check runner architecture
|
||||
run: uname -m
|
||||
|
||||
- name: Check-out repository
|
||||
uses: actions/checkout@v1
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
@ -72,30 +77,31 @@ jobs:
|
||||
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
sudo apt-get install -y libasound2-dev
|
||||
pip install -r requirements.txt
|
||||
pip install nuitka
|
||||
|
||||
- name: Build Executable with Nuitka
|
||||
run: |
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist gofilecli.py --include-data-files=./assets/sounds/Blow_edited.wav=assets/sounds/Blow_edited.wav
|
||||
|
||||
- name: Rename Executable
|
||||
run: mv dist/gofilecli.bin dist/gofilecli
|
||||
uses: Nuitka/Nuitka-Action@main
|
||||
with:
|
||||
nuitka-version: main
|
||||
script-name: gofilecli.py
|
||||
onefile: true
|
||||
|
||||
- name: Upload Artifact[linux-x64]
|
||||
uses: actions/upload-artifact@v3.1.3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: GoFileCLI_linux-x64
|
||||
path: |
|
||||
dist/gofilecli
|
||||
build/gofilecli.bin
|
||||
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
|
||||
steps:
|
||||
- name: Check runner architecture
|
||||
run: uname -m
|
||||
|
||||
- name: Check-out repository
|
||||
uses: actions/checkout@v1
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
@ -112,27 +118,24 @@ jobs:
|
||||
pip install nuitka
|
||||
|
||||
- name: Build Executable with Nuitka
|
||||
# --macos-app-icon=resources/icon.icns
|
||||
run: |
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist --macos-target-arch=arm64 gofilecli.py --include-data-files=./assets/sounds/Blow_edited.wav=assets/sounds/Blow_edited.wav
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist_x86_64 --macos-target-arch=x86_64 gofilecli.py --include-data-files=./assets/sounds/Blow_edited.wav=assets/sounds/Blow_edited.wav
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist --macos-target-arch=arm64 gofilecli.py
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist_x86_64 --macos-target-arch=x86_64 gofilecli.py
|
||||
|
||||
- name: Rename Executable
|
||||
run: |
|
||||
mv dist/gofilecli.bin dist/gofilecli
|
||||
mv dist_x86_64/gofilecli.bin dist_x86_64/gofilecli
|
||||
|
||||
|
||||
- name: Upload Artifact [osx-arm64]
|
||||
uses: actions/upload-artifact@v3.1.3
|
||||
- name: Upload Artifact[osx-arm64]
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: GoFileCLI_osx-x64
|
||||
path: dist_x86_64/gofilecli
|
||||
path: |
|
||||
dist_x86_64/gofilecli.bin
|
||||
|
||||
- name: Upload Artifact [osx-arm64]
|
||||
uses: actions/upload-artifact@v3.1.3
|
||||
- name: Upload Artifact[osx-arm64]
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: GoFileCLI_osx-arm64
|
||||
path: dist/gofilecli
|
||||
path: |
|
||||
dist/gofilecli.bin
|
||||
|
||||
create_draft_release:
|
||||
name: Create Github draft release
|
||||
@ -175,7 +178,7 @@ jobs:
|
||||
attach_to_release:
|
||||
name: Attach native executables to release
|
||||
if: ${{ github.event.inputs.doRelease == 'true' }}
|
||||
needs: [create_draft_release]
|
||||
needs: create_draft_release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get current date
|
||||
@ -188,16 +191,21 @@ jobs:
|
||||
- name: Fetch executables
|
||||
uses: actions/download-artifact@v3
|
||||
|
||||
- name: List downloaded files
|
||||
run: |
|
||||
echo "Listing files in the working directory:"
|
||||
ls -R
|
||||
|
||||
- name: Tar (linux, macOS)
|
||||
run: for dir in *{osx,linux}*; do tar cvzfp "${dir}_${{ env.date }}.tar.gz" "$dir"; done
|
||||
run: |
|
||||
for file in *{osx,linux}*; do
|
||||
if [ -f "$file" ]; then
|
||||
tar cvzfp "${file}_${{ env.date }}.tar.gz" "$file"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Zip (windows)
|
||||
run: for dir in *win*; do zip -r "${dir}_${{ env.date }}.zip" "$dir"; done
|
||||
run: |
|
||||
for file in *win*; do
|
||||
if [ -f "$file" ]; then
|
||||
zip -r "${file}_${{ env.date }}.zip" "$file"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Upload
|
||||
run: |
|
||||
|
4
.gitignore
vendored
4
.gitignore
vendored
@ -133,7 +133,3 @@ encrypt.py
|
||||
/temp
|
||||
.copy
|
||||
.github/workflows/build_latest_ex.yml
|
||||
assets/sounds/Blow.aiff
|
||||
assets/sounds/Blow.mp3
|
||||
assets/sounds/Blow.wav
|
||||
/VP8SWj
|
||||
|
62
README.md
62
README.md
@ -1,60 +1,50 @@
|
||||
# GoFileCLI :
|
||||
Upload or download a file to GoFile.
|
||||
......
|
||||
|
||||
# Install :
|
||||
|
||||
- Linux/MacOS :
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/NohamR/GoFileCLI/main/scripts/install.sh | sudo bash
|
||||
```
|
||||
|
||||
- Windows :
|
||||
Grab latest release from [releases](https://github.com/NohamR/GoFileCLI/releases/latest)
|
||||
|
||||
- Build on your own system :
|
||||
```bash
|
||||
git clone https://github.com/NohamR/GoFileCLI.git
|
||||
apt install ccache patchelf
|
||||
pip install nuitka
|
||||
pip install -r requirements.txt
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist --static-libpython=no gofilecli.py
|
||||
# dist/gofilecli.bin
|
||||
```
|
||||
# Installation :
|
||||
|
||||
## Set env variables :
|
||||
|
||||
Get API token from https://gofile.io/myProfile.
|
||||
Copy folderId from a folder you own.
|
||||
|
||||
- Set up a .env based on [.env.example](.env.example)
|
||||
Windows :
|
||||
```bash
|
||||
setx GOPLOAD_TOKEN "XXXXXXX"
|
||||
setx GOPLOAD_PRIVATE_PARENT_ID "UUID"
|
||||
setx GOPLOAD_ACCOUNT_ID "UUID"
|
||||
```
|
||||
|
||||
(Reluch Command Prompt to take effect)
|
||||
|
||||
- Linux/MacOS :
|
||||
Linux/MacOS :
|
||||
```bash
|
||||
export GOPLOAD_TOKEN="XXXXXXX"
|
||||
export GOPLOAD_PRIVATE_PARENT_ID="UUID"
|
||||
export GOPLOAD_ACCOUNT_ID="UUID"
|
||||
```
|
||||
|
||||
- Windows :
|
||||
```bash
|
||||
setx GOPLOAD_TOKEN "XXXXXXX"
|
||||
setx GOPLOAD_PRIVATE_PARENT_ID "UUID"
|
||||
setx GOPLOAD_ACCOUNT_ID "UUID"
|
||||
```
|
||||
(Reluch Command Prompt to take effect)
|
||||
|
||||
# Usage :
|
||||
Upload a file :
|
||||
```bash
|
||||
gofilecli -i 'file.txt' # to upload a file
|
||||
gofilecli -f folder/ # to upload a folder
|
||||
gofilecli -s # to get stats of your account
|
||||
gofilecli -d https://gofile.io/d/XXXXX # to download a folder
|
||||
gofilecli -i 'file.txt'
|
||||
```
|
||||
|
||||
# Compile on your own system :
|
||||
```bash
|
||||
git clone https://github.com/NohamR/GoFileCLI.git
|
||||
apt install ccache patchelf
|
||||
pip install nuitka
|
||||
pip install -r requirements.txt
|
||||
python -m nuitka --standalone --assume-yes-for-downloads --output-dir=dist --static-libpython=no gofilecli.py
|
||||
# dist/gofilecli.dist/gofilecli.bin
|
||||
```
|
||||
|
||||
# To do :
|
||||
- KeyboardInterrupt + Lost connexion
|
||||
- acc stats
|
||||
- error-rateLimit
|
||||
- env via CLI
|
||||
- finish README.md
|
||||
- chiffrer & dechiffrer uploads
|
||||
- download
|
||||
- build + release
|
||||
- chiffrer et dechiffrer les uploads
|
Binary file not shown.
309
gofilecli.py
Normal file → Executable file
309
gofilecli.py
Normal file → Executable file
@ -6,69 +6,10 @@ import argparse
|
||||
import os
|
||||
import logging
|
||||
import sys
|
||||
from dotenv import load_dotenv, set_key
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import simpleaudio as sa
|
||||
from tqdm import tqdm
|
||||
import json
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Suppress ALSA warnings
|
||||
os.environ['SDL_AUDIODRIVER'] = 'dummy'
|
||||
os.environ['AUDIODEV'] = 'null'
|
||||
|
||||
|
||||
def reqst(url, method ,headers=None, data=None, files=None, params=None, json=None, logger=None):
|
||||
try:
|
||||
if method == "get":
|
||||
response = requests.get(url, headers=headers, data=data, params=params, json=json)
|
||||
elif method == "post":
|
||||
response = requests.post(url, headers=headers, data=data, files=files, params=params, json=json)
|
||||
elif method == "put":
|
||||
response = requests.put(url, headers=headers, data=data, files=files, params=params, json=json)
|
||||
elif method == "delete":
|
||||
response = requests.delete(url, headers=headers, data=data, files=files, params=params, json=json)
|
||||
logger.debug(f"Request to {url} with method {method} returned status code {response.status_code}")
|
||||
json_response = response.json() # If response content is not JSON, this will raise a ValueError
|
||||
return json_response
|
||||
except requests.exceptions.HTTPError as http_err:
|
||||
logger.debug(f"Response: {response.text}")
|
||||
logger.error(f"HTTP error occurred: {http_err}") # Handles HTTP errors (e.g., 404, 500)
|
||||
sys.exit()
|
||||
except requests.exceptions.ConnectionError as conn_err:
|
||||
logger.debug(f"Response: {response.text}")
|
||||
logger.error(f"Connection error occurred: {conn_err}") # Handles network-related errors
|
||||
sys.exit()
|
||||
except requests.exceptions.Timeout as timeout_err:
|
||||
logger.debug(f"Response: {response.text}")
|
||||
logger.error(f"Timeout error occurred: {timeout_err}") # Handles request timeouts
|
||||
sys.exit()
|
||||
except requests.exceptions.RequestException as req_err:
|
||||
logger.debug(f"Response: {response.text}")
|
||||
logger.error(f"An error occurred: {req_err}") # Catches any other requests-related errors
|
||||
sys.exit()
|
||||
except ValueError as json_err:
|
||||
logger.debug(f"Response: {response.text}")
|
||||
logger.error(f"JSON decode error: {json_err}") # Handles issues with JSON decoding
|
||||
sys.exit()
|
||||
|
||||
|
||||
def load_file(file_name: str) -> str:
|
||||
"""
|
||||
Get the correct path to a file, regardless of development or compiled mode.
|
||||
"""
|
||||
return os.path.join(os.path.dirname(__file__), file_name)
|
||||
|
||||
|
||||
def play_sound(logger):
|
||||
try:
|
||||
sound_path = load_file("assets/sounds/Blow_edited.wav")
|
||||
wave_obj = sa.WaveObject.from_wave_file(sound_path)
|
||||
play_obj = wave_obj.play()
|
||||
play_obj.wait_done()
|
||||
except Exception as e:
|
||||
logger.debug(f"An error occurred while playing sound: {e}")
|
||||
|
||||
|
||||
def set_env_var_unix(name, value, shell="bash"):
|
||||
@ -96,15 +37,12 @@ def format_file_size(file=None, num_bytes=None):
|
||||
file_size_bytes = num_bytes
|
||||
else:
|
||||
file_size_bytes = os.path.getsize(file)
|
||||
size_in_kb = file_size_bytes / 1024
|
||||
size_in_mb = file_size_bytes / (1024 * 1024)
|
||||
size_in_gb = file_size_bytes / (1024 * 1024 * 1024)
|
||||
if size_in_gb >= 1:
|
||||
return size_in_gb, "GB"
|
||||
elif size_in_mb >= 1:
|
||||
return size_in_mb, "MB"
|
||||
else:
|
||||
return size_in_kb, "KB"
|
||||
return size_in_mb, "MB"
|
||||
|
||||
|
||||
def file_size(file=None, num_bytes=None):
|
||||
@ -115,10 +53,9 @@ def file_size(file=None, num_bytes=None):
|
||||
def calculate_upload_speed(file, start_time):
|
||||
elapsed_time_seconds = time.time() - start_time
|
||||
file_size, size_unit = format_file_size(file)
|
||||
|
||||
if size_unit == "GB":
|
||||
average_speed = (file_size * 1024) / elapsed_time_seconds # Convert GB to MB and calculate MB/s
|
||||
speed_unit = "MB/s"
|
||||
average_speed = file_size / elapsed_time_seconds # GB/s
|
||||
speed_unit = "GB/s"
|
||||
else:
|
||||
average_speed = file_size / elapsed_time_seconds # MB/s
|
||||
speed_unit = "MB/s"
|
||||
@ -143,16 +80,9 @@ def get_file_paths(folderPath):
|
||||
return filePaths
|
||||
|
||||
|
||||
def check_folderPath(path):
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
|
||||
def getservers(logger):
|
||||
servers = []
|
||||
# response = requests.get("https://api.gofile.io/servers").json()
|
||||
response = reqst("https://api.gofile.io/servers", logger=logger, method="get")
|
||||
response = requests.get("https://api.gofile.io/servers").json()
|
||||
if response["status"] == "ok":
|
||||
for server in response["data"]["servers"]:
|
||||
servers.append(server["name"])
|
||||
@ -163,65 +93,22 @@ def getservers(logger):
|
||||
return None
|
||||
|
||||
|
||||
def ping_server(url, logger, num_requests=4, delay=0.1):
|
||||
response_times = []
|
||||
for _ in range(num_requests):
|
||||
try:
|
||||
start_time = time.time()
|
||||
response = requests.head(url)
|
||||
response_time = time.time() - start_time
|
||||
if response.status_code == 200:
|
||||
response_times.append(response_time)
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"Error: {e}")
|
||||
time.sleep(delay)
|
||||
if response_times:
|
||||
avg_response = sum(response_times) / len(response_times)
|
||||
return avg_response
|
||||
else:
|
||||
return float('inf')
|
||||
|
||||
|
||||
def test_servers(servers, logger):
|
||||
best_server = None
|
||||
best_time = float('inf')
|
||||
for server in servers:
|
||||
logger.debug(f"Pinging {server}...")
|
||||
url = f"https://{server}.gofile.io"
|
||||
avg_time = ping_server(url, logger)
|
||||
logger.debug(f"Average response time for {server}: {avg_time:.2f} ms")
|
||||
if avg_time < best_time:
|
||||
best_time = avg_time
|
||||
best_server = server
|
||||
if best_server:
|
||||
logger.debug(f"\nThe best server is {best_server} with an average response time of {best_time:.2f} ms.")
|
||||
else:
|
||||
logger.error("All pings failed.")
|
||||
return best_server
|
||||
|
||||
|
||||
def get_stats(logger):
|
||||
headers = {'authorization': f'Bearer {TOKEN}',}
|
||||
# data = requests.get(f'https://api.gofile.io/accounts/{ACCOUNT_ID}', headers=headers).json()
|
||||
data = reqst(f'https://api.gofile.io/accounts/{ACCOUNT_ID}', headers=headers, logger=logger, method="get")
|
||||
if data["status"] == "ok":
|
||||
stats = data["data"]["statsCurrent"]
|
||||
logger.info("Account stats:")
|
||||
logger.info(f"Total files: {stats['fileCount']}")
|
||||
logger.info(f"Total folders: {stats['folderCount']}")
|
||||
size = file_size(num_bytes=stats['storage'])
|
||||
logger.info(f"Total size: {size}")
|
||||
traffic = file_size(num_bytes=stats['trafficWebDownloaded'])
|
||||
logger.info(f"Total traffic: {traffic}")
|
||||
else:
|
||||
logger.error(f"{data}")
|
||||
return None
|
||||
data = requests.get(f'https://api.gofile.io/accounts/{ACCOUNT_ID}', headers=headers).json()
|
||||
stats = data["data"]["statsCurrent"]
|
||||
logger.info("Account stats:")
|
||||
logger.info(f"Total files: {stats['fileCount']}")
|
||||
logger.info(f"Total folders: {stats['folderCount']}")
|
||||
size = file_size(num_bytes=stats['storage'])
|
||||
logger.info(f"Total size: {size}")
|
||||
traffic = file_size(num_bytes=stats['trafficWebDownloaded'])
|
||||
logger.info(f"Total traffic: {traffic}")
|
||||
|
||||
|
||||
def get_rootfolder(logger):
|
||||
headers = {'authorization': f'Bearer {TOKEN}',}
|
||||
# data = requests.get(f'https://api.gofile.io/accounts/{ACCOUNT_ID}', headers=headers).json()
|
||||
data = reqst(f'https://api.gofile.io/accounts/{ACCOUNT_ID}', headers=headers, logger=logger, method="get")
|
||||
data = requests.get(f'https://api.gofile.io/accounts/{ACCOUNT_ID}', headers=headers).json()
|
||||
root_folder = data.get("data", {}).get("rootFolder", {})
|
||||
if root_folder:
|
||||
return root_folder
|
||||
@ -233,8 +120,7 @@ def get_rootfolder(logger):
|
||||
def get_code(folderId, logger):
|
||||
headers = {'authorization': f'Bearer {TOKEN}',}
|
||||
params = (('wt', '4fd6sg89d7s6'),('cache', 'false'),)
|
||||
# data = requests.get(f'https://api.gofile.io/contents/{folderId}', headers=headers, params=params).json()
|
||||
data = reqst(f'https://api.gofile.io/contents/{folderId}', headers=headers, params=params, logger=logger, method="get")
|
||||
data = requests.get(f'https://api.gofile.io/contents/{folderId}', headers=headers, params=params).json()
|
||||
code = data.get("data", {}).get("code", {})
|
||||
if code:
|
||||
return code
|
||||
@ -244,10 +130,10 @@ def get_code(folderId, logger):
|
||||
|
||||
|
||||
def get_children(id, logger):
|
||||
# if len(id) == 36:
|
||||
headers = {'authorization': f'Bearer {TOKEN}',}
|
||||
params = (('wt', '4fd6sg89d7s6'),('cache', 'false'),)
|
||||
# data = requests.get(f'https://api.gofile.io/contents/{id}', headers=headers, params=params).json()
|
||||
data = reqst(f'https://api.gofile.io/contents/{id}', headers=headers, params=params, logger=logger, method="get")
|
||||
data = requests.get(f'https://api.gofile.io/contents/{id}', headers=headers, params=params).json()
|
||||
children = data.get("data", {}).get("children", {})
|
||||
if children:
|
||||
return children
|
||||
@ -267,12 +153,11 @@ def createfolder(parentFolderId, folderName, logger):
|
||||
data = {"parentFolderId": parentFolderId, "folderName": folderName}
|
||||
else:
|
||||
data = {"parentFolderId": parentFolderId}
|
||||
# response = requests.post("https://api.gofile.io/contents/createFolder", headers=headers, json=data).json()
|
||||
response = reqst("https://api.gofile.io/contents/createFolder", headers=headers, json=data, logger=logger, method="post")
|
||||
response = requests.post("https://api.gofile.io/contents/createFolder", headers=headers, json=data).json()
|
||||
if response["status"] == "ok":
|
||||
name = response["data"]["name"]
|
||||
code = response["data"]["code"]
|
||||
folderId = response["data"]["id"]
|
||||
folderId = response["data"]["folderId"]
|
||||
logger.debug(f"""Folder {name} created with code {code} and folderId {folderId}""")
|
||||
return folderId
|
||||
else:
|
||||
@ -280,57 +165,15 @@ def createfolder(parentFolderId, folderName, logger):
|
||||
return None
|
||||
|
||||
|
||||
def read_in_chunks(file_object, CHUNK_SIZE):
|
||||
while True:
|
||||
data = file_object.read(CHUNK_SIZE)
|
||||
if not data:
|
||||
break
|
||||
yield data
|
||||
|
||||
|
||||
def uploadfile(serverName, folderId, filePath, logger):
|
||||
# reference : https://api.video/blog/tutorials/upload-a-big-video-file-using-python/
|
||||
headers = {"Authorization": f"Bearer {TOKEN}"}
|
||||
files = {
|
||||
'file': (filePath, open(filePath, 'rb')),
|
||||
'folderId': (None, folderId),
|
||||
}
|
||||
start_time = time.time()
|
||||
# CHUNK_SIZE = 6000000
|
||||
# content_size = os.stat(filePath).st_size
|
||||
# f = open(filePath, "rb")
|
||||
# index = 0
|
||||
# offset = 0
|
||||
# headers = {"Authorization": f"Bearer {TOKEN}", 'content-type': 'multipart/form-data',}
|
||||
# with tqdm(total=content_size, unit='B', unit_scale=True, desc='Uploading', leave=False) as progress_bar:
|
||||
# for chunk in read_in_chunks(f, CHUNK_SIZE):
|
||||
# offset = index + len(chunk)
|
||||
# headers['Content-Range'] = 'bytes %s-%s/%s' % (index, offset - 1, content_size)
|
||||
# index = offset
|
||||
# try:
|
||||
# # file = {"file": chunk, 'folderId': (None, folderId)}
|
||||
# # response = requests.post(f"https://{serverName}.gofile.io/contents/uploadfile", files=file, headers=headers)
|
||||
# # files = {"file": chunk}
|
||||
# # data = {"folderId": folderId}
|
||||
# files = {"file": chunk,}
|
||||
# response = requests.post(f"https://{serverName}.gofile.io/contents/uploadfile",files=files,headers=headers)
|
||||
# logger.debug("r: %s, Content-Range: %s" % (response, headers['Content-Range']))
|
||||
# progress_bar.update(len(chunk))
|
||||
# except Exception as e:
|
||||
# logger.error(f"Error: {e}")
|
||||
# logger.debug(f"{response.text}")
|
||||
# response = response.json()
|
||||
command = [
|
||||
"curl",
|
||||
"-X", "POST",
|
||||
f"https://{serverName}.gofile.io/contents/uploadfile",
|
||||
"-H", f"Authorization: Bearer {TOKEN}",
|
||||
"-F", f"file=@{filePath}",
|
||||
"-F", f"folderId={folderId}",
|
||||
]
|
||||
response = subprocess.run(command, capture_output=True, text=True)
|
||||
try:
|
||||
response_json = json.loads(response.stdout)
|
||||
except json.JSONDecodeError:
|
||||
logger.error("Failed to parse response as JSON.")
|
||||
return None
|
||||
response = requests.post(f"https://{serverName}.gofile.io/contents/uploadfile", headers=headers, files=files).json()
|
||||
speed, elapsed_time = calculate_upload_speed(filePath, start_time)
|
||||
response = response_json
|
||||
if response["status"] == "ok":
|
||||
logger.debug(response)
|
||||
name = response["data"]["name"]
|
||||
@ -343,11 +186,10 @@ def uploadfile(serverName, folderId, filePath, logger):
|
||||
return None
|
||||
|
||||
|
||||
def actionFolder(folderId, attributeValue, logger):
|
||||
def actionFolder(folderId, attributeValue):
|
||||
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {TOKEN}"}
|
||||
data = {"attribute": "public", "attributeValue": attributeValue}
|
||||
# response = requests.put(f"https://api.gofile.io/contents/{folderId}/update", headers=headers, json=data).json()
|
||||
response = reqst(f"https://api.gofile.io/contents/{folderId}/update", headers=headers, json=data, logger=logger, method="put")
|
||||
response = requests.put(f"https://api.gofile.io/contents/{folderId}/update", headers=headers, json=data).json()
|
||||
if response["status"] == "ok":
|
||||
return True
|
||||
else:
|
||||
@ -362,25 +204,17 @@ def upload(filePath, folderPath, folderName, parentFolderId, private, logger):
|
||||
files = get_file_paths(folderPath)
|
||||
if not files:
|
||||
logger.error("No files found in folder")
|
||||
sys.exit()
|
||||
sys.exit("No files found in folder")
|
||||
else:
|
||||
if os.path.exists(filePath):
|
||||
files = [filePath]
|
||||
else:
|
||||
logger.error("File not found")
|
||||
sys.exit()
|
||||
sys.exit("File not found")
|
||||
|
||||
# Getting servers
|
||||
servers = getservers(logger)
|
||||
if servers:
|
||||
if len(servers) > 1: # If there are multiple servers, check the size of the files
|
||||
if max([os.path.getsize(file) for file in files]) > 100 * 1024 * 1024: # 100 MB in bytes
|
||||
logger.debug("One of the file have a size > 100 MB. Fetching best server...")
|
||||
serverName = test_servers(servers, logger)
|
||||
else:
|
||||
serverName = random.choice(servers)
|
||||
else:
|
||||
serverName = servers[0]
|
||||
serverName = random.choice(servers)
|
||||
logger.debug(f"Selected server: {serverName}")
|
||||
|
||||
if folderName and parentFolderId:
|
||||
@ -397,60 +231,48 @@ def upload(filePath, folderPath, folderName, parentFolderId, private, logger):
|
||||
parentFolderId = parentFolderId
|
||||
logger.debug(f"FolderId: {parentFolderId}")
|
||||
else:
|
||||
# parentFolderId = PRIVATE_PARENT_ID
|
||||
logger.info(f"Creating folder: {folderName} for PRIVATE_PARENT_ID: {PRIVATE_PARENT_ID}")
|
||||
folderId = createfolder(PRIVATE_PARENT_ID, None, logger)
|
||||
parentFolderId = folderId
|
||||
parentFolderId = None
|
||||
logger.debug(f"FolderId: {parentFolderId}")
|
||||
|
||||
for file in files:
|
||||
if parentFolderId:
|
||||
logger.info(f"Uploading file: '{file}' ({file_size(file)}) to: '{parentFolderId}' on: '{serverName}'")
|
||||
else:
|
||||
logger.info(f"Uploading file: '{file}' ({file_size(file)}) on: '{serverName}'")
|
||||
logger.info(f"Uploading file: {file} ({file_size(file)}) on: {serverName}")
|
||||
downloadPage, parentFolderId, speed, elapsed_time = uploadfile(serverName, parentFolderId, file, logger)
|
||||
logger.info(f"File uploaded to: {downloadPage} in {elapsed_time} at {speed}")
|
||||
|
||||
if not private:
|
||||
action = actionFolder(parentFolderId, "true", logger)
|
||||
action = actionFolder(parentFolderId, "true")
|
||||
if action:
|
||||
logger.info("Folder made public")
|
||||
else:
|
||||
logger.error(f"{action}")
|
||||
else:
|
||||
action = actionFolder(parentFolderId, "false", logger)
|
||||
action = actionFolder(parentFolderId, "false")
|
||||
if action:
|
||||
logger.info("Folder made private")
|
||||
else:
|
||||
logger.error(f"{action}")
|
||||
play_sound(logger)
|
||||
else:
|
||||
time.sleep(10)
|
||||
sys.exit()
|
||||
time.spleed(10)
|
||||
sys.exit("No server available")
|
||||
|
||||
|
||||
def downloadFile(downloadUrl, path, logger):
|
||||
start_time = time.time()
|
||||
headers = {"Authorization": f"Bearer {TOKEN}"}
|
||||
response = requests.get(downloadUrl, headers=headers, stream=True)
|
||||
# response = reqst(downloadUrl, headers=headers, logger=logger, method="get")
|
||||
total_size = int(response.headers.get('content-length', 0))
|
||||
|
||||
with open(path, "wb") as f, tqdm(total=total_size, unit='B', unit_scale=True, desc='Downloading', leave=False) as progress_bar:
|
||||
for chunk in response.iter_content(1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
progress_bar.update(len(chunk))
|
||||
response = requests.get(downloadUrl, headers=headers)
|
||||
with open(path, "wb") as f:
|
||||
f.write(response.content)
|
||||
logger.debug(f"File downloaded: {path}")
|
||||
speed, elapsed_time = calculate_upload_speed(path, start_time)
|
||||
return speed, elapsed_time
|
||||
|
||||
|
||||
def download(folderId, folderPath, force, logger):
|
||||
def download(folderId, logger, folderPath=None):
|
||||
if 'https' in folderId:
|
||||
folderId = folderId.split('/')[-1]
|
||||
if len(folderId) == 36:
|
||||
folderId = get_code(folderId)
|
||||
files = []
|
||||
logger.info("Fetching files")
|
||||
logger.debug("FolderId: %s", folderId)
|
||||
@ -464,28 +286,17 @@ def download(folderId, folderPath, force, logger):
|
||||
files.append(children[child])
|
||||
else:
|
||||
folderIdList.append(children[child]['id'])
|
||||
nbdone = 0
|
||||
logger.info(f"Starting download of {len(files)} files")
|
||||
for file in files:
|
||||
logger.info(f"Downloading file {nbdone}/{len(files)}: {file['name']} ({file_size(num_bytes=file['size'])})")
|
||||
logger.info(f"Downloading file: {file['name']} ({file_size(num_bytes=file['size'])})")
|
||||
downloadUrl = file['link']
|
||||
name = file['name']
|
||||
if folderPath:
|
||||
folderPath = check_folderPath(folderPath)
|
||||
path = os.path.join(folderPath, name)
|
||||
else:
|
||||
folderPath = check_folderPath(os.path.join(os.getcwd(), folderId))
|
||||
path = os.path.join(folderPath, name)
|
||||
if os.path.exists(path) and not force:
|
||||
logger.warning(f"File {name} already exists skipping (set --force to overwrite)")
|
||||
elif os.path.exists(path) and force:
|
||||
logger.warning(f"File {name} already exists overwriting")
|
||||
speed, elapsed_time = downloadFile(downloadUrl, path, logger)
|
||||
logger.info(f"File download to: {path} in {elapsed_time} at {speed}")
|
||||
else:
|
||||
speed, elapsed_time = downloadFile(downloadUrl, path, logger)
|
||||
logger.info(f"File download to: {path} in {elapsed_time} at {speed}")
|
||||
nbdone += 1
|
||||
play_sound(logger)
|
||||
path = name
|
||||
speed, elapsed_time = downloadFile(downloadUrl, path, logger)
|
||||
logger.info(f"File download to: {path} in {elapsed_time} at {speed}")
|
||||
|
||||
|
||||
def opt():
|
||||
@ -505,20 +316,21 @@ def opt():
|
||||
exclusive_group.add_argument('--stats', "-s", action='store_true', help='Display account stats.')
|
||||
|
||||
exclusive_group.add_argument("--download", "-d", type=str, help="Id or code to the folder to be downloaded")
|
||||
parser.add_argument("--output", "-o", type=str, help="¨Path to the folder to be downloaded")
|
||||
parser.add_argument("--force", "-fo", action="store_true", help="Overwrite existing files")
|
||||
|
||||
# parser.add_argument_group
|
||||
# parser.add_mutually_exclusive_group
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def init():
|
||||
args = opt()
|
||||
# print('args: ', args)
|
||||
# print(sys.argv)
|
||||
log_format = "%(asctime)s %(levelname)s: %(message)s"
|
||||
logging.basicConfig(level=getattr(logging, args.log_level.upper()),format=log_format,datefmt="%H:%M:%S",)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
global TOKEN
|
||||
global PRIVATE_PARENT_ID
|
||||
global ACCOUNT_ID
|
||||
@ -532,7 +344,7 @@ def init():
|
||||
set_env_var("GOPLOAD_TOKEN", args.token)
|
||||
else:
|
||||
logger.error("Error: GOPLOAD_TOKEN not found, add GOPLOAD_TOKEN to your environment variables")
|
||||
sys.exit()
|
||||
sys.exit("Error: GOPLOAD_TOKEN not found, add GOPLOAD_TOKEN to your environment variables")
|
||||
|
||||
if not PRIVATE_PARENT_ID:
|
||||
if args.private_parent_id:
|
||||
@ -545,12 +357,7 @@ def init():
|
||||
set_env_var("GOPLOAD_PRIVATE_PARENT_ID", args.private_parent_id)
|
||||
else:
|
||||
logger.error("Error: GOPLOAD_PRIVATE_PARENT_ID not found, add GOPLOAD_PRIVATE_PARENT_ID to your environment variables")
|
||||
sys.exit()
|
||||
|
||||
# No params:
|
||||
if len(sys.argv) == 1:
|
||||
logger.error("No arguments specified. Use -h for help")
|
||||
sys.exit("")
|
||||
sys.exit("Error: GOPLOAD_PRIVATE_PARENT_ID not found, add GOPLOAD_PRIVATE_PARENT_ID to your environment variables")
|
||||
|
||||
# Stats section
|
||||
if args.stats:
|
||||
@ -564,13 +371,13 @@ def init():
|
||||
elif args.file:
|
||||
if args.folder:
|
||||
logger.error("Both file and folder specified")
|
||||
sys.exit()
|
||||
sys.exit("Both file and folder specified")
|
||||
else:
|
||||
upload(args.file, args.folder, args.name, args.parent, args.private, logger)
|
||||
elif args.folder:
|
||||
if args.file:
|
||||
logger.error("Both file and folder specified")
|
||||
sys.exit()
|
||||
sys.exit("Both file and folder specified")
|
||||
else:
|
||||
upload(args.file, args.folder, args.name, args.parent, args.private, logger)
|
||||
|
||||
@ -580,12 +387,8 @@ def init():
|
||||
|
||||
# Download section
|
||||
elif args.download:
|
||||
download(args.download, args.output, args.force, logger)
|
||||
download(args.download, logger)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
init()
|
||||
except KeyboardInterrupt:
|
||||
print("\nExiting...")
|
||||
sys.exit()
|
||||
init()
|
@ -1,5 +1,3 @@
|
||||
cryptography==39.0.1
|
||||
python-dotenv==1.0.1
|
||||
Requests==2.32.3
|
||||
simpleaudio==1.0.4
|
||||
tqdm==4.65.0
|
||||
|
@ -1,25 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "Error: No tag provided."
|
||||
echo "Usage: $0 <tag>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
tag=$1
|
||||
|
||||
source ~/miniconda3/etc/profile.d/conda.sh
|
||||
conda activate 310
|
||||
pip install -r requirements.txt
|
||||
python -m nuitka --onefile --assume-yes-for-downloads --output-dir=dist --static-libpython=no gofilecli.py --include-data-files=./assets/sounds/Blow_edited.wav=assets/sounds/Blow_edited.wav
|
||||
mv dist/gofilecli.bin ./gofilecli
|
||||
|
||||
mkdir -p GoFileCLI_linux-arm64
|
||||
mv ./gofilecli GoFileCLI_linux-arm64/
|
||||
|
||||
date=$(date +"%Y%m%d")
|
||||
tar cvzfp "GoFileCLI_linux-arm64_${date}.tar.gz" GoFileCLI_linux-arm64
|
||||
|
||||
gh release upload ${tag} "GoFileCLI_linux-arm64_${date}.tar.gz"
|
||||
|
||||
rm -rf GoFileCLI_linux-arm64
|
@ -1,63 +0,0 @@
|
||||
#!/bin/bash
|
||||
owner="NohamR"
|
||||
repo="GoFileCLI"
|
||||
latest_release=$(curl -s https://api.github.com/repos/$owner/$repo/releases/latest)
|
||||
|
||||
tag_name=$(echo "$latest_release" | jq -r '.tag_name')
|
||||
assets=$(echo "$latest_release" | jq -r '.assets[] | .name')
|
||||
|
||||
echo "Latest release tag: $tag_name"
|
||||
|
||||
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
|
||||
|
||||
if [[ "$OS" == "darwin" ]]; then
|
||||
OS="osx"
|
||||
fi
|
||||
|
||||
ARCH=$(uname -m)
|
||||
|
||||
if [[ "$ARCH" == "x86_64" ]]; then
|
||||
ARCH="x64"
|
||||
elif [[ "$ARCH" == "aarch64" || "$ARCH" == "arm64" ]]; then
|
||||
ARCH="arm64"
|
||||
else
|
||||
echo "Unsupported architecture: $ARCH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
expected_file="GoFileCLI_${OS}-${ARCH}_*.tar.gz"
|
||||
|
||||
if [[ "$OS" == "windows" ]]; then
|
||||
expected_file="GoFileCLI_${OS}-${ARCH}_*.zip"
|
||||
fi
|
||||
|
||||
selected_asset=$(echo "$assets" | grep -E "^GoFileCLI_${OS}-${ARCH}_.*")
|
||||
|
||||
if [[ -z "$selected_asset" ]]; then
|
||||
echo "No matching asset found for OS: $OS, Architecture: $ARCH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Selected asset: $selected_asset"
|
||||
|
||||
download_url=$(echo "$latest_release" | jq -r --arg name "$selected_asset" '.assets[] | select(.name == $name) | .browser_download_url')
|
||||
|
||||
echo "Downloading $selected_asset from $download_url..."
|
||||
curl -LO "$download_url"
|
||||
if [[ ! -f "$selected_asset" ]]; then
|
||||
echo "Download failed."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
tar -xzf "$selected_asset"
|
||||
extracted_dir=$(find . -type d -name "GoFileCLI*" | head -n 1)
|
||||
if [[ -d "$extracted_dir" ]]; then
|
||||
sudo mv "$extracted_dir/gofilecli" /usr/local/bin/
|
||||
chmod +x /usr/local/bin/gofilecli
|
||||
echo "Installation completed. You can now use 'gofilecli'."
|
||||
else
|
||||
echo "Failed to find the extracted directory."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rm -rf "$selected_asset" "$extracted_dir"
|
@ -1,45 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
BINARY_NAME="gofilecli"
|
||||
|
||||
BINARY_PATH=$(which $BINARY_NAME)
|
||||
|
||||
if [[ -z "$BINARY_PATH" ]]; then
|
||||
echo "$BINARY_NAME is not installed or not found in PATH."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Found $BINARY_NAME at $BINARY_PATH."
|
||||
read -p "Are you sure you want to uninstall $BINARY_NAME? [y/N]: " confirm
|
||||
|
||||
if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
|
||||
echo "Uninstallation cancelled."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sudo rm -f "$BINARY_PATH"
|
||||
|
||||
if [[ ! -f "$BINARY_PATH" ]]; then
|
||||
echo "$BINARY_NAME has been successfully uninstalled."
|
||||
else
|
||||
echo "Failed to uninstall $BINARY_NAME."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Checking for any leftover files or directories..."
|
||||
leftovers=$(find /usr/local/bin -name "$BINARY_NAME" 2>/dev/null)
|
||||
|
||||
if [[ -n "$leftovers" ]]; then
|
||||
echo "Found leftover files:"
|
||||
echo "$leftovers"
|
||||
read -p "Do you want to remove these leftover files? [y/N]: " cleanup_confirm
|
||||
|
||||
if [[ "$cleanup_confirm" == "y" || "$cleanup_confirm" == "Y" ]]; then
|
||||
sudo rm -rf $leftovers
|
||||
echo "Leftover files removed."
|
||||
else
|
||||
echo "Leftover files not removed."
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Uninstallation complete."
|
Loading…
x
Reference in New Issue
Block a user