Skip to content

Instantly share code, notes, and snippets.

@Aluriak
Created June 10, 2020 22:23
Show Gist options
  • Save Aluriak/f45f61ad69e7b861dc4ffd090a3db66e to your computer and use it in GitHub Desktop.
Save Aluriak/f45f61ad69e7b861dc4ffd090a3db66e to your computer and use it in GitHub Desktop.
Little helper to upload a file or a set of file in a library of a seafile instance.
#!/usr/bin/python3
"""Little helper to upload a file or a set of file in a library of a seafile instance,
using requests.
"""
import os
import glob
import json
import argparse
import getpass
import requests
def parse_cli():
"""Simpler version"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('files', nargs='+', type=str, help='file(s)')
parser.add_argument('lib', type=str, help='library to populate')
parser.add_argument('--indir', '-i', default='/', type=str, help='directory to create in the library in which the files will be added')
parser.add_argument('--user', '-u', default='lucas@bourneuf.net', type=str, help='username')
parser.add_argument('--password', '-p', type=str, help='password', default=None)
parser.add_argument('--seafile-port', type=int, help='local seafile instance port', default=8082)
parser.add_argument('--seafile-url', '-s', type=str, help='local seafile instance url', default='https://example.seafile.com/')
return parser.parse_args()
def upload_files(args):
# let's get the token allowing us to do things
url = f'https://{args.seafile_url}/api2/'
data = {'username': args.user, 'password': args.password or getpass.getpass()}
ret = requests.post(url + 'auth-token/', data=data)
if 'token' not in ret.json():
print('failure:', ret, '\n', ret.json())
return
token = {'Authorization': f'Token {ret.json()["token"]}'}
print(f'Connected with token {ret.json()["token"]}')
# let's find the requested library
ret = requests.get(url + 'repos/', headers=token)
if 'detail' in ret.json():
print('failure:', ret, '\n', ret.json())
return
# print('success:', ret, '\n', ret.json())
for lib in ret.json():
if lib['name'] == args.lib:
lib_id = lib['id']
if 'w' not in lib['permission']:
print(f"Library named \"{args.lib}\" found, but you don't have write access on it.")
return
break
else: # none found
print(f"No library named \"{args.lib}\" found. Maybe you don't have access ?")
return
# add, if given, a directory
# TODO
# get an upload link
ret = requests.get(url + f'repos/{lib_id}/upload-link/', headers=token)
if 'detail' in ret.json():
print('failure:', ret, '\n', ret.json())
return
# print('success:', ret, '\n', ret.json())
upload_url = ret.json()
print(f'Upload will be sent to "{upload_url}"')
# upload the files
if not args.indir.startswith('/'): # absolute path needed
args.indir = '/' + args.indir
if args.indir != '/':
print('For a mysterious reason, uploading files to specific directory is not functional.')
if input('Continue nonetheless ? [y/N]').lower() not in {'o', 'y', 'yes'}:
return
for glob_fname in args.files:
at_least_one_file = False
for fname in glob.glob(glob_fname):
at_least_one_file = True
print(f'Sending "{fname}"…', end='', flush=False)
files = {'filename': os.path.basename(fname), 'file': open(fname, 'rb'), 'parent_dir': args.indir}
# print('', files, end='', flush=False)
ret = requests.post(upload_url, headers=token, files=files)
print(' OK:', ret.text)
if not at_least_one_file:
print(f'No file matched by glob "{glob_fname}"')
return ret.text
if __name__ == "__main__":
upload_files(parse_cli())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment