Skip to content

Instantly share code, notes, and snippets.

@PegasisForever
Last active July 25, 2023 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PegasisForever/d38901e2e3da1ebf9f772740287bc6b9 to your computer and use it in GitHub Desktop.
Save PegasisForever/d38901e2e3da1ebf9f772740287bc6b9 to your computer and use it in GitHub Desktop.
upload files to nextcloud and get shareable link
#!/usr/bin/python3
import sys
import os
import requests
import time
from requests.auth import HTTPBasicAuth
import xml.etree.ElementTree as ET
def get_timed_filename(filePath):
baseName = os.path.basename(filePath)
filename, file_extension = os.path.splitext(baseName)
return filename+'-'+str(round(time.time()))+file_extension
def upload_share(user, password, baseUrl, filePath, remoteFolder, quiet):
timedFileName = get_timed_filename(filePath)
# upload
if not quiet:
print('Uploading file '+filePath+'.....')
response = requests.put(baseUrl+"/remote.php/dav/files/"+user+remoteFolder+'/'+timedFileName,
auth=HTTPBasicAuth(user, password),
data=open(filePath, 'rb'))
status = response.status_code
if status == 201:
if not quiet:
print('File uploaded scuccessfully.')
elif status == 204:
if not quiet:
print('File already exists.')
elif status < 299:
if not quiet:
print('File uploaded, status code: ' + str(status)+'.')
else:
print('File failed to upload, status code: ' +
str(status)+', response: '+response.text)
return (False, None)
# share
if not quiet:
print("Getting the file share link.....")
response = requests.post(baseUrl+"/ocs/v2.php/apps/files_sharing/api/v1/shares",
auth=HTTPBasicAuth(user, password),
headers={'OCS-APIRequest': 'true'},
data={'shareType': '3', 'path': remoteFolder+'/'+timedFileName})
if status >= 200 and status < 300:
if not quiet:
print('Got the share link scuccessfully.')
xml = ET.fromstring(response.text)
return (True, xml.find('./data/url').text)
else:
print('Failed to get the share link, status code: ' +
str(status)+', response: '+response.text)
return (False, None)
if len(sys.argv) == 1 or '--help' in sys.argv:
print(
"""nextcloud-uploader - upload files to nextcloud and get shareable link
Usage: nextcloud-uploader [OPTION] [<file names>...]
Options:
-q, --quiet don't print logs
-d, --direct get direct link of the file
-p, --preview get preview link of the file (for images and pdfs)
-u, --user username:password username and password of your nextcloud account
-b, --baseurl base url of your nextcloud instance, example: https://cloud.pegasis.site
-r, --remotefolder remote folder your files will be uploaded to, example: /typora-images
""")
quiet = False
directLink = False
previewLink = False
user = ''
password = ''
baseUrl = ''
remoteFolder = ''
filePaths = []
i = 1
while i < len(sys.argv):
arg = sys.argv[i]
if arg == '-q' or arg == '--quiet':
quiet = True
i += 1
elif arg == '-d' or arg == '--direct':
directLink = True
i += 1
elif arg == '-p' or arg == '--preview':
previewLink = True
i += 1
elif arg == '-u' or arg == '--user':
auth = sys.argv[i+1].split(':')
user = auth[0]
password = auth[1]
i += 2
elif arg == '-b' or arg == '--baseurl':
baseUrl = sys.argv[i+1]
i += 2
elif arg == '-r' or arg == '--remotefolder':
remoteFolder = sys.argv[i+1]
i += 2
else:
filePaths.append(arg)
i += 1
sharedUrls = []
for filePath in filePaths:
(success, url) = upload_share(user, password,
baseUrl, filePath, remoteFolder, quiet)
if success:
sharedUrls.append(url)
for url in sharedUrls:
if directLink:
print(url+'/download')
elif previewLink:
print(url+'/preview')
else:
print(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment