home-backup/home_backup/client.py

92 lines
3.1 KiB
Python

import asyncio
from . import defaults, utils
#
# Base connector
#
def run_command(async_func, user_path:str=None):
async def runner():
# Connect to user socket
nonlocal user_path
if user_path is None:
user_path = defaults.USER_PATH
if user_path is None:
raise RuntimeError("User service socket path isn't set.")
sock = utils.Connection()
await sock.init(user_path)
# Run async function
await async_func(sock)
asyncio.run(runner())
#
# Backups
#
def backup_add_gen(name:str, btype:str, info):
async def backup_add(con:utils.Connection):
result = await con.call({"operation": "backup-add", "name": name, "type": btype, "info": info})
if result["status"] != "success":
if result["status"] == "fail-already-exists":
print("Backup %s already exists." % name)
exit(1)
else:
raise RuntimeError("Wasn't able to add remote.") # TODO: Show error
return backup_add
#
# Remotes
#
def remote_add_gen(name:str, rtype:str, info):
async def remote_add(con:utils.Connection):
result = await con.call({"operation": "remote-add", "name": name, "type": rtype, "info": info})
if result["status"] != "success":
if result["status"] == "fail-already-exists":
print("Remote %s already exists." % name)
exit(1)
else:
raise RuntimeError("Wasn't able to add remote.") # TODO: Show error
return remote_add
def remote_list_gen(name:str=None):
async def remote_list(con:utils.Connection):
# Get remotes
result = await con.call({"operation": "remote-list"})
if result["status"] != "success":
raise RuntimeError("Wasn't able to get remotes list.") # TODO: Show error
# Output remotes
if name is None:
for i in result["data"].keys():
print(i)
else:
if name not in result["data"]:
print("Can't find remote %s." % name)
exit(1)
else:
max_length = max(map(lambda x: len(x), result["data"][name].keys())) + 1
for iID, i in sorted(result["data"][name].items(), key=lambda x: x[0]):
print("%s:%s%s" % (iID, " " * (max_length - len(iID)), str(i)))
return remote_list
def remote_delete_gen(names:list):
# Check
if isinstance(names, str):
raise TypeError("names have to be a listing type.")
names = list(names)
for i in names:
if not isinstance(i, str):
raise TypeError("names list have to contain string.")
# Procedure
async def remote_delete(con:utils.Connection):
for i in names:
result = await con.call({"operation": "remote-delete", "name": i})
if result["status"] != "success":
if result["status"] == "failed-not-existing":
print("Remote %s doesn't exists." % i)
exit(1)
else:
raise RuntimeError("Wasn't able to delete remote.") # TODO: Show error
return remote_delete