Skip to content

Commit

Permalink
Add an option to upload multiple files to the same folder
Browse files Browse the repository at this point in the history
  • Loading branch information
Alyetama committed Oct 5, 2022
1 parent 1b31414 commit 387207c
Show file tree
Hide file tree
Showing 4 changed files with 132 additions and 59 deletions.
55 changes: 38 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,30 @@ pip install gofilepy
## ⌨️ Usage

```
➜ gofile --help
usage: gofile [-h] [-o] [-e] [-vv] [-v] path [path ...]
usage: gofilepy [-h] [-s] [-o] [-e] [-vv] [-v] path [path ...]
Example: gofile <file/folder_path>
positional arguments:
path Path to the file(s) and/or folder(s)
optional arguments:
-h, --help show this help message and exit
-o, --open-urls Open the URL(s) in the browser when the upload is complete
(macOS-only)
-e, --export Export upload response(s) to a JSON file
-vv, --verbose Show more information
-v, --version Show program's version number and exit
path Path to the file(s) and/or folder(s)
options:
-h, --help show this help message and exit
-s, --to-single-folder
Upload multiple files to the same folder. All files
will share the same URL. This option requires a valid
token exported as: `GOFILE_TOKEN`
-o, --open-urls Open the URL(s) in the browser when the upload is
complete (macOS-only)
-e, --export Export upload response(s) to a JSON file
-vv, --verbose Show more information
-v, --version show program's version number and exit
```

## 📕 Examples

### Example 1: Uploading one file

```sh
➜ gofile foo.txt
╭───────────────────────────────────────────╮
Expand All @@ -50,6 +53,7 @@ Uploading progress: ━━━━━━━━━━━━━━━━━━━━
```

### Example 2: Uploading multiple files/directories

```bash
➜ gofile foo.txt bar.txt foobar.txt foo/
╭───────────────────────────────────────────╮
Expand All @@ -71,9 +75,25 @@ Uploading progress: ━━━━━━━━━━━━━━━━━━━━
Uploading progress: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00
```

### Example 3: Verbose output
### Example 3: Uploading multiple files to the same URL

This option requires a Gofile token (see: [## Misc.](#misc)).

```bash
➜ gofile -s foo.txt bar.txt
╭───────────────────────────────────────────╮
│ Files: │
│ foo.txt │
│ bar.txt │
│ Download page: https://gofile.io/d/bFwawd │
╰───────────────────────────────────────────╯
Uploading progress: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00
```

### Example 4: Verbose output

```sh
➜ gofile foo.txt -vv
➜ gofile -vv foo.txt
╭──────────────────────────────────────────────────────────────────────────────╮
│ { │
"foo.txt": { │
Expand All @@ -96,9 +116,10 @@ Uploading progress: ━━━━━━━━━━━━━━━━━━━━
Uploading progress: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00
```
### Example 4: Exporting the API response to a JSON file
### Example 5: Exporting the API response to a JSON file
```sh
➜ gofile foo.txt -e
➜ gofile -e foo.txt
╭───────────────────────────────────────────╮
│ File: foo.txt │
│ Download page: https://gofile.io/d/8t79Lz │
Expand Down Expand Up @@ -137,7 +158,7 @@ Exported data to: gofile_export_1653950555.json
### 🔑 Optional: Saving uploads to your Gofile account
If you want the files to be uploaded to a specific account, you can export your gofile token, which can be retrieved from the profile page, as an environment variable.
If you want the files to be uploaded to a specific account, you can export your gofile token, which can be retrieved from the [profile page](https://gofile.io/myProfile), as an environment variable `GOFILE_TOKEN`.
```sh
export GOFILE_TOKEN='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
Expand Down
2 changes: 1 addition & 1 deletion gofilepy/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '0.2.3'
__version__ = '0.3.0'
132 changes: 92 additions & 40 deletions gofilepy/gofile.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
import mimetypes
import os
import subprocess
import sys
import time
from datetime import datetime
from glob import glob
from pathlib import Path
from platform import platform
from typing import Optional

import requests
from rich import print as rprint
Expand All @@ -21,7 +23,7 @@
from .__version__ import __version__


def upload(file, best_server):
def upload(file: str, best_server: str, folder_id: Optional[str] = None):
f_obj = Path(file)
content_type = mimetypes.guess_type(f_obj)[0]
upload_url = f'https://{best_server}.gofile.io/uploadFile'
Expand All @@ -33,7 +35,10 @@ def upload(file, best_server):
try:
resp = requests.post(
upload_url,
data={'token': os.getenv('GOFILE_TOKEN')},
data={
'token': os.getenv('GOFILE_TOKEN'),
'folderId': folder_id
},
files={'file': (f_obj.name, f_data, content_type)})
break
except requests.exceptions.ConnectionError:
Expand All @@ -48,34 +53,11 @@ def upload(file, best_server):
return resp


def opts():
parser = argparse.ArgumentParser(
description='Example: gofile <file/folder_path>')
parser.add_argument(
'-o',
'--open-urls',
help='Open the URL(s) in the browser when the upload is complete '
'(macOS-only)',
action='store_true')
parser.add_argument('-e',
'--export',
help='Export upload response(s) to a JSON file',
action='store_true')
parser.add_argument('-vv',
'--verbose',
help='Show more information',
action='store_true')
parser.add_argument('path',
nargs='+',
help='Path to the file(s) and/or folder(s)')
parser.add_argument('-v',
'--version',
action='version',
version=f'%(prog)s {__version__}')
return parser.parse_args()


def gofile_upload(path, verbose=False, export=False, open_urls=False):
def gofile_upload(path: list,
to_single_folder: bool = False,
verbose: bool = False,
export: bool = False,
open_urls: bool = False):
highlighter = JSONHighlighter()

get_server = requests.get('https://apiv2.gofile.io/getServer')
Expand All @@ -84,6 +66,11 @@ def gofile_upload(path, verbose=False, export=False, open_urls=False):
files = []

for _path in path:
if not Path(_path).exists():
rprint(
f'[red]ERROR: [dim blue]"{Path(_path).absolute()}"[/dim blue] '
'does not exist! [/red]')
continue
if Path(_path).is_dir():
dir_items = glob(str(Path(f'{_path}/**/*')), recursive=True)
local_files = [x for x in dir_items if not Path(x).is_dir()]
Expand All @@ -95,11 +82,26 @@ def gofile_upload(path, verbose=False, export=False, open_urls=False):

export_data = []
urls = []
folder_id = None
n = 0

for file in track(files, description='[magenta]Uploading progress:'):
upload_resp = upload(file, best_server, folder_id).json()

if to_single_folder and not os.getenv('GOFILE_TOKEN'):
rprint('[red]ERROR: Gofile token is required when passing '
'`--to-single-folder`![/red]\n[dim red]You can find your '
'account token on this page: '
'[u][blue]https://gofile.io/myProfile[/blue][/u]\nCopy it '
'then export it as `GOFILE_TOKEN`. For example:\n'
'export GOFILE_TOKEN=\'xxxxxxxxxxxxxxxxx\'[/dim red]')
sys.exit(1)
elif to_single_folder and os.getenv('GOFILE_TOKEN'):
folder_id = upload_resp['data']['parentFolder']

for file in track(files, description='[blue]Uploading progress:'):
upload_resp = upload(file, best_server).json()
ts = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
record = {file: {'timestamp': ts, 'response': upload_resp}}
file_abs = str(Path(file).absolute())
record = {'file': file_abs, 'timestamp': ts, 'response': upload_resp}

url = upload_resp['data']['downloadPage']
urls.append(url)
Expand All @@ -108,15 +110,25 @@ def gofile_upload(path, verbose=False, export=False, open_urls=False):
highlighted_resp = highlighter(json.dumps(record, indent=2))
rprint(Panel(highlighted_resp))

else:
elif not to_single_folder:
rprint(
Panel.fit(
f'[yellow]File:[/yellow] [blue]{file}[/blue]\n'
f'[yellow]Download page:[/yellow] [blue]{url}[/blue]'))

f'[yellow]Download page:[/yellow] [u][blue]{url}[/blue][/u]'
))
if export:
export_data.append(record)

if not urls:
sys.exit()

if to_single_folder:
files = '\n'.join([str(Path(x).absolute()) for x in files])
rprint(
Panel.fit(f'[yellow]Files:[/yellow]\n[blue]{files}[/blue]\n'
'[yellow]Download page:[/yellow] '
f'[u][blue]{urls[0]}[/blue][/u]'))

if export:
export_fname = f'gofile_export_{int(time.time())}.json'
with open(export_fname, 'w') as j:
Expand All @@ -127,14 +139,54 @@ def gofile_upload(path, verbose=False, export=False, open_urls=False):
if 'macOS' in platform() and open_urls:
for url in urls:
subprocess.call(['open', f'{url}'])
if to_single_folder:
break


def opts():
parser = argparse.ArgumentParser(
description='Example: gofile <file/folder_path>')
parser.add_argument(
'-s',
'--to-single-folder',
help=
'Upload multiple files to the same folder. All files will share the '
'same URL. This option requires a valid token exported as: '
'`GOFILE_TOKEN`',
action='store_true')
parser.add_argument(
'-o',
'--open-urls',
help='Open the URL(s) in the browser when the upload is complete '
'(macOS-only)',
action='store_true')
parser.add_argument('-e',
'--export',
help='Export upload response(s) to a JSON file',
action='store_true')
parser.add_argument('-vv',
'--verbose',
help='Show more information',
action='store_true')
parser.add_argument('path',
nargs='+',
help='Path to the file(s) and/or folder(s)')
parser.add_argument('-v',
'--version',
action='version',
version=f'%(prog)s {__version__}')
return parser.parse_args()


def main():
args = opts()
gofile_upload(path=args.path,
verbose=args.verbose,
export=args.export,
open_urls=args.open_urls)
gofile_upload(
path=args.path,
to_single_folder=args.to_single_folder,
verbose=args.verbose,
export=args.export,
open_urls=args.open_urls,
)


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "gofilepy"
version = "0.2.3"
version = "0.3.0"
description = "Upload files to Gofile.io"
authors = ["Mohammad Alyetama <[email protected]>"]
license = "MIT"
Expand Down

0 comments on commit 387207c

Please sign in to comment.