Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions filecloudapi/datastructures.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ class FileListEntry:
issyncable: bool
isdatasyncable: bool
etag: ETag
# Empty when the server does not report them: createdepochutc (getfilelist,
# and fileinfo of a file, 23.253 and later), systemcreatedepochutc (fileinfo,
# only when the server stores the OS creation date)
createdepochutc: str = ""
systemcreatedepochutc: str = ""


@dataclass
Expand Down Expand Up @@ -255,7 +260,7 @@ class PolicyEntry:
class PolicyList:
"""Convienience class represents policy list"""

entries: list[PolicyEntry] = []
entries: list[PolicyEntry]

def first(self) -> PolicyEntry | None:
if len(self.entries) >= 1:
Expand All @@ -267,6 +272,8 @@ def __iter__(self):

def __init__(self, a_response: Element):
""""""
# Per instance: a class level list collected the policies of every listing
self.entries = []
self._set_entries(response=a_response)

def _set_entries(self, response: Element):
Expand All @@ -286,13 +293,15 @@ def _set_entries(self, response: Element):
class ServerSettings:
"""Convienience class represents server settings"""

entries: dict = {}
entries: dict

def __iter__(self):
return iter(self.entries)

def __init__(self, a_response: Element):
""""""
# Per instance: a class level dict collected the settings of every response
self.entries = {}
self._set_entries(response=a_response)

def _set_entries(self, response: Element):
Expand All @@ -305,6 +314,14 @@ def _set_entries(self, response: Element):
self.entries[list(elem)[0].text] = list(elem)[1].text


@dataclass
class SystemStatus:
"""Fields of getsystemstatus, empty when the server does not report them"""

appversion: str
uploadchunksize: str


@dataclass
class StorageRootDetails:
type: str
Expand Down
157 changes: 135 additions & 22 deletions filecloudapi/fcserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
SortDir,
SyncDeltaItem,
SyncFolder,
SystemStatus,
TeamFolderInfo,
UserStatus,
)
Expand Down Expand Up @@ -197,6 +198,14 @@ def _extract_etag(self, etag: str):
else:
return etag

@staticmethod
def _upload_query(params: Dict) -> str:
"""
Encode the query of an upload request
"""
# WEBUI DOES NOT ENCODE THE ! of a public share path (/SHARED/!<token>/...)
return urlencode(params).replace("%2FSHARED%2F%21", "%2FSHARED%2F!")

def login(self) -> None:
"""
Try to login to FC server with the credentials
Expand Down Expand Up @@ -320,6 +329,8 @@ def shared_opt(txt: Optional[str]) -> SharedType:
entry.findtext("./issyncable", "1") == "1",
entry.findtext("./isdatasyncable", "1") == "1",
entry.findtext("./etag", ""),
entry.findtext("./createdepochutc", ""),
entry.findtext("./systemcreatedepochutc", ""),
)

def getfilelist(
Expand Down Expand Up @@ -379,6 +390,17 @@ def bool_opt(txt: Union[None, str]) -> bool:
entries,
)

def getsystemstatus(self) -> SystemStatus:
"""
Returns the server version and the upload chunk size (MiB)
"""
resp = self._api_call("/core/getsystemstatus", {})

return SystemStatus(
resp.findtext("./status/appversion", ""),
resp.findtext("./status/uploadchunksize", ""),
)

def fileinfo_no_retry(self, path: str) -> FileListEntry:
"""
Returns information about file/directory 'path'
Expand Down Expand Up @@ -847,12 +869,7 @@ def close(self):
if ifetag is not None:
params["ifetag"] = ifetag

params_str = urlencode(params)

if params_str.find("%2FSHARED%2F%21"):
params_str = params_str.replace(
"%%2FSHARED%2F%21", "%2FSHARED%2F!"
) # WEBUI DOES NOT ENCODE THE !
params_str = self._upload_query(params)

resp = self.session.post(
self.url + "/core/upload?" + params_str,
Expand Down Expand Up @@ -902,12 +919,7 @@ def close(self):
if data_size is not None:
params["filesize"] = data_size

params_str = urlencode(params)

if params_str.find("%2FSHARED%2F%21"):
params_str = params_str.replace(
"%%2FSHARED%2F%21", "%2FSHARED%2F!"
) # WEBUI DOES NOT ENCODE THE !
params_str = self._upload_query(params)

if complete == 1:
headers[SEND_ETAG_HEADER] = "1"
Expand Down Expand Up @@ -994,10 +1006,60 @@ def quickshare(self, sharelocation: str, adminproxyuserid: str = "") -> FCShare:
str_to_bool(resp.findtext("./share/allowpublicuploadonly", "")),
)

def deleteshare(self, share: FCShare) -> None:
def deleteshare(self, share: FCShare, adminproxyuserid: str = "") -> None:
"""
Delete share. A share owned by another user (for example a team folder
share) is deleted through the admin proxy 'adminproxyuserid'
"""
resp = self._api_call(
"/core/deleteshare",
{"shareid": share.shareid},
{"shareid": share.shareid, "adminproxyuserid": adminproxyuserid},
)
self._raise_exception_from_command(resp)

def updateshare(
self,
share: FCShare,
sharename: str,
allowpublicaccess: bool,
adminproxyuserid: str = "",
) -> None:
"""
Rename share and set its public access

The server resets the share settings this call does not send: the
expiry, the upload size limit, the download limit and count and
hidenotifications, and the password of a share that is public before
the call. Use it on shares that do not rely on those settings.
"""
resp = self._api_call(
"/core/updateshare",
{
"shareid": share.shareid,
"sharename": sharename,
"allowpublicaccess": 1 if allowpublicaccess else 0,
"adminproxyuserid": adminproxyuserid,
},
)

# Success answers with the updated share, a failure with a meta error
# or a command result
if resp.find("./share") is None:
message = (
resp.findtext("./meta/error")
or resp.findtext("./command/message")
or "Failed to update share"
)
self._raise_exception_from_server_message(message)

def deleteuserfromshare(self, share: FCShare, userid: str) -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

userid has to be the user's email. The server validates it as one (ShareRouter.php, addRequiredParam('userid', Valid::VALID_EMAIL, Filter::LOWER_CASE)) and answers 422 for a user name. Worth naming it email or saying so in the docstring.

"""
Remove user from share. 'userid' is the user's email, the server
answers a user name with HTTP 422
"""
resp = self._api_call(
"/core/deleteuserfromshare",
{"shareid": share.shareid, "userid": userid},
)
self._raise_exception_from_command(resp)

Expand Down Expand Up @@ -1761,7 +1823,7 @@ def admin_addnewuser(
"displayname": username,
"email": email,
"password": password,
"authtype ": authtype, # 0 for default auth and 1 for AD
"authtype": authtype, # 0 for default auth and 1 for AD
"status": status, # full(1), guest(0), external(3) or disabled user(2)
},
)
Expand Down Expand Up @@ -2011,8 +2073,10 @@ def admin_getgroups(

return group_list

def admin_createnewgroup(self, groupname: str):
"""List all policies"""
def admin_createnewgroup(self, groupname: str) -> str:
"""
Create group and return its group id
"""
resp = self._api_call(
"/admin/addgroup",
{"op": "addgroup", "groupname": groupname},
Expand All @@ -2021,6 +2085,8 @@ def admin_createnewgroup(self, groupname: str):
if resp.findtext("./group/groupname") is None:
raise ServerError("", "Failed to create group")

return resp.findtext("./group/groupid", "")

def admin_groupisinshare(
self,
share: FCShare,
Expand Down Expand Up @@ -2096,6 +2162,57 @@ def admin_addmembertogroup(self, groupid: str, username: str) -> None:
)
self._raise_exception_from_command(resp)

def admin_deletememberfromgroup(self, groupid: str, userid: str) -> None:
"""
Remove user from group
"""
resp = self._api_call(
"/admin/deletememberfromgroup",
{"op": "deletememberfromgroup", "groupid": groupid, "userid": userid},
)
self._raise_exception_from_command(resp)

def admin_addusertoexternal(
self, externalid: str, userid: str, writemode: str = "1"
) -> None:
"""
Allow user access to external
"""
resp = self._api_call(
"/admin/addusertoexternal",
{
"op": "addusertoexternal",
"externalid": externalid,
"userid": userid,
"writemode": writemode,
},
)
self._raise_exception_from_command(resp)

def admin_deleteuserfromexternal(self, externalid: str, userid: str) -> None:
"""
Revoke user access to external
"""
resp = self._api_call(
"/admin/deleteuserfromexternal",
{
"op": "deleteuserfromexternal",
"externalid": externalid,
"userid": userid,
},
)
self._raise_exception_from_command(resp)

def admin_deleteexternal(self, externalid: str) -> None:
"""
Delete external
"""
resp = self._api_call(
"/admin/deleteexternal",
{"op": "deleteexternal", "externalid": externalid},
)
self._raise_exception_from_command(resp)

def admin_setgroupaccessforshare(
self,
share: Optional[FCShare],
Expand Down Expand Up @@ -2416,8 +2533,4 @@ def admin_deletegroup(self, groupid: str) -> bool:
{"op": "deletegroup", "groupid": groupid},
)

result = resp.findtext("./command/result")
if result == "0":
return True
else:
return False
return resp.findtext("./command/result") == "1"
38 changes: 38 additions & 0 deletions filecloudapi/tests/test_datastructures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Copyright (c) 2024 FileCloud. All Rights Reserved.

import xml.etree.ElementTree as ET

from filecloudapi.datastructures import PolicyList, ServerSettings


def _policies(*names: str) -> ET.Element:
policies = "".join(
f"<policy><policyid>id_{name}</policyid><policyname>{name}</policyname></policy>"
for name in names
)
return ET.fromstring(f"<policies>{policies}</policies>")


def _settings(**settings: str) -> ET.Element:
entries = "".join(
f"<setting><param>{name}</param><value>{value}</value></setting>"
for name, value in settings.items()
)
return ET.fromstring(f"<settings>{entries}</settings>")


def test_policy_list_holds_only_its_own_response():
first = PolicyList(_policies("a"))
second = PolicyList(_policies("b"))

assert [p.policyname for p in first] == ["a"]
assert [p.policyname for p in second] == ["b"]
assert second.first().policyid == "id_b" # type: ignore


def test_server_settings_hold_only_their_own_response():
first = ServerSettings(_settings(TONIDOCLOUD_A="1"))
second = ServerSettings(_settings(TONIDOCLOUD_B="2"))

assert first.entries == {"TONIDOCLOUD_A": "1"}
assert second.entries == {"TONIDOCLOUD_B": "2"}
Loading