selfhostedops-stack/filesync/client/api.py

81 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""ep19fs API-Helfer (Clients). Zugang aus /root/ep19fs/env (0600), nie ausgeben.
api.py P cmd [args] P = nc|oc|sf
rmtree PATH Ordner auf dem Server löschen und Papierkorb leeren
count PATH Dateien (rekursiv) und Bytes unter PATH auf dem Server
exists PATH HTTP-Status eines Pfads
"""
import os, sys, json, time, requests, xml.etree.ElementTree as ET
from urllib.parse import quote, unquote
E = {k: v.strip("'") for k, v in (l.strip().split('=', 1) for l in open(os.environ.get('EP19ENV','/root/ep19fs/env')) if '=' in l and not l.startswith('#'))}
P, cmd = sys.argv[1], sys.argv[2]
s = requests.Session()
DAV = 'DAV:'
def nc():
u = E['NC_URL']; s.auth = (E['NC_USER'], E['NC_PASS']); return u, f"{u}/remote.php/dav/files/{E['NC_USER']}"
def oc():
u = E['OC_URL']; s.auth = (E['OC_USER'], E['OC_TOKEN']); return u, f"{u}/remote.php/dav/spaces/{E['OC_SPACE']}"
def sfdav():
u = E['SF_URL']; s.auth = (E['SF_USER'], E['SF_PASS']); return u, f"{u}/seafdav"
def base():
return {'nc': nc, 'oc': oc, 'sf': sfdav}[P]()
def propfind(url, depth='infinity'):
r = s.request('PROPFIND', url, headers={'Depth': depth}, data='<?xml version="1.0"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:getcontentlength/></d:prop></d:propfind>')
return r
def walk(url):
files = 0; size = 0
r = propfind(url, 'infinity')
if r.status_code == 207 and P != 'sf':
for resp in ET.fromstring(r.content).findall(f'{{{DAV}}}response'):
isdir = resp.find(f'.//{{{DAV}}}collection') is not None
if not isdir:
files += 1; cl = resp.find(f'.//{{{DAV}}}getcontentlength'); size += int(cl.text) if cl is not None and cl.text else 0
return files, size
# Tiefe 1 rekursiv
stack = [url]
while stack:
cur = stack.pop(); r = propfind(cur, '1')
if r.status_code != 207: return None, r.status_code
for i, resp in enumerate(ET.fromstring(r.content).findall(f'{{{DAV}}}response')):
if i == 0: continue
href = resp.find(f'{{{DAV}}}href').text
if resp.find(f'.//{{{DAV}}}collection') is not None:
stack.append(url.split('/remote.php')[0].split('/seafdav')[0] + href if href.startswith('/') else href)
else:
files += 1; cl = resp.find(f'.//{{{DAV}}}getcontentlength'); size += int(cl.text) if cl is not None and cl.text else 0
return files, size
if cmd == 'count':
u, d = base(); print(*walk(d + '/' + quote(sys.argv[3].strip('/'))))
elif cmd == 'exists':
u, d = base(); print(propfind(d + '/' + quote(sys.argv[3].strip('/')), '0').status_code)
elif cmd == 'ls':
u, d = base(); r = propfind(d + '/' + quote(sys.argv[3].strip('/')), '1')
names = [unquote(x.find(f'{{{DAV}}}href').text.rstrip('/').split('/')[-1]) for x in ET.fromstring(r.content).findall(f'{{{DAV}}}response')][1:]
print(r.status_code, sorted(names))
elif cmd == 'restore': # restore NAME ORIGPATH: Element aus dem Papierkorb zurückholen
u, d = base(); name, orig = sys.argv[3], sys.argv[4]
if P == 'nc':
tb = f"{u}/remote.php/dav/trashbin/{E['NC_USER']}/trash"
body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:nc="http://nextcloud.org/ns"><d:prop><nc:trashbin-filename/><nc:trashbin-original-location/></d:prop></d:propfind>'
else:
tb = f"{u}/remote.php/dav/spaces/trash-bin/{E['OC_SPACE']}"
body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"><d:prop><oc:trashbin-original-filename/><oc:trashbin-original-location/></d:prop></d:propfind>'
t0 = time.time(); r = s.request('PROPFIND', tb, headers={'Depth': '1'}, data=body)
items = []
for x in ET.fromstring(r.content).findall(f'{{{DAV}}}response')[1:]:
loc = [e.text for e in x.iter() if e.tag.endswith('original-location')]
items.append((x.find(f'{{{DAV}}}href').text, loc[0] if loc else ''))
print('Papierkorb:', len(items), 'Einträge', [l for h, l in items])
href = [h for h, l in items if l and l.strip('/') == orig.strip('/')][0]
host = u.split('/remote.php')[0]
dest = f"{u}/remote.php/dav/trashbin/{E['NC_USER']}/restore/{name}" if P == 'nc' else f"{d}/{quote(orig.strip('/'))}"
r = s.request('MOVE', host + href, headers={'Destination': dest})
print(f'MOVE {r.status_code}, Wiederherstellung auf dem Server {time.time()-t0:.2f} s')
elif cmd == 'mkcol':
u, d = base(); r = s.request('MKCOL', d + '/' + quote(sys.argv[3].strip('/'))); print('MKCOL', r.status_code)
elif cmd == 'rmtree':
u, d = base(); r = s.delete(d + '/' + quote(sys.argv[3].strip('/'))); print('DELETE', r.status_code)
if P == 'nc':
r = s.delete(f"{u}/remote.php/dav/trashbin/{E['NC_USER']}/trash"); print('empty trash', r.status_code)
elif P == 'oc':
r = s.delete(f"{u}/remote.php/dav/spaces/trash-bin/{E['OC_SPACE']}"); print('empty trash', r.status_code)