Skip to content

Commit

Permalink
Fix scrutinizer issues + fix login error
Browse files Browse the repository at this point in the history
  • Loading branch information
luffah committed May 4, 2021
1 parent f1f4521 commit e95e19d
Show file tree
Hide file tree
Showing 17 changed files with 215 additions and 150 deletions.
2 changes: 1 addition & 1 deletion requirements.in
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
requests>=2.0.1
pytest
pytest>=4.6
38 changes: 21 additions & 17 deletions src/nextcloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,17 @@ class NextCloud(object):
... # some actions #
"""

def __init__(self, endpoint, user=None, password=None, json_output=True, auth=None, session_kwargs=None):
self.query_components = []
self._session = Session(
def __init__(self, endpoint=None,
user=None, password=None, json_output=True, auth=None,
session_kwargs=None,
session=None):
self.session = session or Session(
url=endpoint, user=user, password=password, auth=auth,
session_kwargs=session_kwargs
)
self.json_output = json_output
for functionality_class in API_WRAPPER_CLASSES:
json_able = getattr(functionality_class, 'JSON_ABLE', False)
require_client = getattr(
functionality_class, 'REQUIRE_CLIENT', False)
functionality_instance = functionality_class(
self._session,
json_output=(json_able and json_output),
client=(require_client and self))
functionality_instance = functionality_class(self)
for potential_method in dir(functionality_instance):
if not potential_method.startswith('_'):
if not callable(getattr(functionality_instance, potential_method)):
Expand All @@ -56,11 +52,11 @@ def __init__(self, endpoint, user=None, password=None, json_output=True, auth=No

@property
def user(self):
return self._session.user
return self.session.user

@property
def url(self):
return self._session.url
return self.session.url

def __enter__(self):
self.login()
Expand All @@ -71,14 +67,22 @@ def __exit__(self, *args):

def login(self, user=None, password=None, auth=None):
self.logout()
self._session.login(user=user, password=password, auth=auth)
return self.session.login(user=user, password=password, auth=auth,
client=self)

def with_attr(self, **kwargs):
if 'auth' in kwargs:
return self.with_auth(**kwargs)
if 'session_kwargs' in kwargs:
return self.with_auth(self.session.auth, **kwargs)
return self.__class__(session=self.session, **kwargs)

def with_auth(self, auth=None, **kwargs):
init_kwargs = {'session_kwargs': self._session._session_kwargs,
init_kwargs = {'session_kwargs': self.session._session_kwargs,
'json_output': self.json_output}
init_kwargs.update(kwargs)
return (self.__class__)(self._session.url, auth=auth, **init_kwargs)
return self.__class__(self.session.url, auth=auth, **init_kwargs)

def logout(self):
if self._session.session:
self._session.logout()
if self.session.session:
self.session.logout()
2 changes: 1 addition & 1 deletion src/nextcloud/api_wrappers/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ def get_activities(self, since=None, limit=None, object_type=None, object_id=Non
sort=sort
)
if params['object_type'] and params['object_id']:
return self.requester.get(url="filter", params=params)
return self.requester.get(url="filter", params=params)
return self.requester.get(params=params)
4 changes: 3 additions & 1 deletion src/nextcloud/api_wrappers/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ def get_apps(self, filter=None):
:param filter: str, optional "enabled" or "disabled"
:return:
"""
params = {"filter": filter}
params = {
"filter": filter
}
return self.requester.get(params=params)

def get_app(self, app_id):
Expand Down
12 changes: 6 additions & 6 deletions src/nextcloud/api_wrappers/group_folders.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ def set_permissions_to_group_folder(self, fid, gid, permissions):
:param permissions (int): The new permissions for the group as attribute of Permission class
:returns: resquester response
"""
url = '/'.join([str(fid), 'groups', gid])
return self.requester.post(url=url, data={'permissions': permissions})
url = "/".join([str(fid), "groups", gid])
return self.requester.post(url=url, data={"permissions": permissions})

def set_quota_of_group_folder(self, fid, quota):
"""
Expand All @@ -86,8 +86,8 @@ def set_quota_of_group_folder(self, fid, quota):
:param quota (int/str): The new quota for the folder in bytes, user -3 for unlimited
:returns: resquester response
"""
url = '/'.join([str(fid), 'quota'])
return self.requester.post(url, {'quota': quota})
url = "/".join([str(fid), "quota"])
return self.requester.post(url, {"quota": quota})

def rename_group_folder(self, fid, mountpoint):
"""
Expand All @@ -97,5 +97,5 @@ def rename_group_folder(self, fid, mountpoint):
:param mountpoint (str): name for the new folder
:returns: resquester response
"""
url = '/'.join([str(fid), 'mountpoint'])
return self.requester.post(url=url, data={'mountpoint': mountpoint})
url = "/".join([str(fid), "mountpoint"])
return self.requester.post(url=url, data={"mountpoint": mountpoint})
46 changes: 29 additions & 17 deletions src/nextcloud/api_wrappers/systemtags.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@


class Tag(PropertySet):
""" Define a Tag properties"""
_attrs = [
Prop('oc:id'),
Prop('oc:display-name', json='name', default='default_tag_name'),
Expand All @@ -22,19 +23,27 @@ class Tag(PropertySet):
class SystemTags(WebDAVApiWrapper):
""" SystemTags API wrapper """
API_URL = '/remote.php/dav/systemtags'
JSON_ABLE = True

def get_sytemtag(self, name, fields=None, json_output=None):
"""
Get attributes of a nammed tag
:param name (str): tag name
:param fields (<list>str): field names
:returns: requester response with <list>Tag in data
"""
if not fields:
fields = Tag._fields
resp = self.requester.propfind(data=Tag.build_xml_propfind(
fields={'oc': ['display-name'] + fields}))
resp = self.requester.propfind(
data=Tag.build_xml_propfind(fields={
'oc': ['display-name'] + fields
}))
if json_output is None:
json_output = self.json_output
return Tag.from_response(resp,
json_output=json_output,
init_attrs=True,
filtered=(lambda t: t.display_name == name))
filtered=lambda t: t.display_name == name)

def get_systemtags(self):
"""
Expand All @@ -43,8 +52,9 @@ def get_systemtags(self):
:returns: requester response with <list>Tag in data
"""
resp = self.requester.propfind(
data=Tag.build_xml_propfind(use_default=True))
return Tag.from_response(resp, json_output=(self.json_output))
data=Tag.build_xml_propfind(use_default=True)
)
return Tag.from_response(resp, json_output=self.json_output)

def create_systemtag(self, name, **kwargs):
"""
Expand All @@ -53,9 +63,12 @@ def create_systemtag(self, name, **kwargs):
:param name: tag name
:returns: requester response with tag id as data
"""
data = (Tag.default_get)(name=name, **kwargs)
resp = self.requester.post(data=(json.dumps(data)), headers={
'Content-Type': 'application/json'})
data = Tag.default_get(name=name, **kwargs)
resp = self.requester.post(
data=json.dumps(data),
headers={
'Content-Type': 'application/json'
})
if resp.is_ok:
resp.data = int(
resp.raw.headers['Content-Location'].split('/')[(-1)])
Expand All @@ -64,7 +77,7 @@ def create_systemtag(self, name, **kwargs):
def delete_systemtag(self, name=None, tag_id=None):
"""
Delete systemtag
:param name (str): tag name, not required it tag_id is provided
:tag_id (int): tag id, not required if name is provided
Expand All @@ -74,16 +87,15 @@ def delete_systemtag(self, name=None, tag_id=None):
resp = self.get_sytemtag(name, ['id'], json_output=False)
if resp.data:
tag_id = resp.data[0].id
elif tag_id:
resp = self.requester.delete(url=(str(tag_id)))
if not tag_id: # lint only
return None
resp = self.requester.delete(url=(str(tag_id)))
return resp


class SystemTagsRelation(WebDAVApiWrapper):
""" SystemTagsRelation API wrapper """
API_URL = '/remote.php/dav/systemtags-relations/files'
JSON_ABLE = True
REQUIRE_CLIENT = True

def _get_fileid_from_path(self, path):
""" Tricky function to fetch file """
Expand Down Expand Up @@ -121,7 +133,8 @@ def get_systemtags_relation(self, file_id=None, **kwargs):
:returns: requester response with <list>Tag in data
"""
file_id, = self._arguments_get(['file_id'], locals())
file_id, = self._arguments_get(['file_id'], dict(file_id=file_id,
**kwargs))
data = Tag.build_xml_propfind()
resp = self.requester.propfind(additional_url=file_id, data=data)
return Tag.from_response(resp, json_output=(self.json_output))
Expand All @@ -138,7 +151,7 @@ def delete_systemtags_relation(self, file_id=None, tag_id=None, **kwargs):
:returns: requester response
"""
file_id, tag_id = self._arguments_get([
'file_id', 'tag_id'], locals())
'file_id', 'tag_id'], dict(file_id=file_id, tag_id=tag_id, **kwargs))
resp = self.requester.delete(url=('{}/{}'.format(file_id, tag_id)))
return resp

Expand All @@ -163,6 +176,5 @@ def add_systemtags_relation(self, file_id=None, tag_id=None, **kwargs):
tag_id = resp.data
if not file_id:
raise ValueError('No file found')
data = Tag.build_xml_propfind()
resp = self.requester.put(url=('{}/{}'.format(file_id, tag_id)))
return resp
1 change: 0 additions & 1 deletion src/nextcloud/api_wrappers/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
class User(base.ProvisioningApiWrapper):
""" User API wrapper """
API_URL = "/ocs/v1.php/cloud/users"
REQUIRE_CLIENT = True

def add_user(self, uid, passwd):
"""
Expand Down
4 changes: 1 addition & 3 deletions src/nextcloud/api_wrappers/user_ldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,7 @@ def edit_ldap_config(self, config_id, data):
:returns: requester response
"""
prepared_data = {
'configData[{}]'.format(key): value
for key, value in data.items()}
prepared_data = {'configData[{}]'.format(key): value for key, value in data.items()}
return self.requester.put(config_id, data=prepared_data)

def ldap_cache_flush(self, config_id):
Expand Down
5 changes: 2 additions & 3 deletions src/nextcloud/api_wrappers/webdav.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,12 @@ def _extract_resource_type(file_property):
file_type = list(file_property)
if file_type:
return re.sub('{.*}', '', file_type[0].tag)
return 'file'


class WebDAV(WebDAVApiWrapper):
""" WebDav API wrapper """
API_URL = "/remote.php/dav/files"
JSON_ABLE = True
REQUIRE_CLIENT = True

def _get_path(self, path):
if path:
Expand Down Expand Up @@ -287,7 +286,7 @@ def get_file_property(self, path, field, tag='oc'):
if ':' in field:
tag, field = field.split(':')
get_file_prop_xpath = '{DAV:}propstat/d:prop/%s:%s' % (tag, field)
data = (File.build_xml_propfind)(**{tag: [field]})
data = File.build_xml_propfind(**{tag: [field]})
resp = self.requester.propfind(additional_url=(self._get_path(path)), headers={'Depth': str(0)},
data=data)
response_data = resp.data
Expand Down
27 changes: 16 additions & 11 deletions src/nextcloud/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@


class MetaWrapper(type):
def __new__(meta, name, bases, attrs):
cls = type.__new__(meta, name, bases, attrs)
if (cls.API_URL != NotImplementedError and cls.VERIFIED):
API_WRAPPER_CLASSES.append(cls)
return cls
""" Meta class to register wrappers """
def __new__(cls, name, bases, attrs):
new_cls = type.__new__(cls, name, bases, attrs)
if (new_cls.API_URL != NotImplementedError and new_cls.VERIFIED):
API_WRAPPER_CLASSES.append(new_cls)
return new_cls


class BaseApiWrapper(object, six.with_metaclass(MetaWrapper)):
Expand All @@ -40,19 +41,19 @@ class BaseApiWrapper(object, six.with_metaclass(MetaWrapper)):
API_URL = NotImplementedError
VERIFIED = True
JSON_ABLE = True
REQUIRE_CLIENT = False
REQUIRE_USER = False
REQUESTER = Requester

def __init__(self, session, json_output=None, client=None, user=None):
self.json_output = json_output
def __init__(self, client=None):
self.client = client
self.user = user
self.requester = self.REQUESTER(session, json_output=json_output)
self.requester = self.REQUESTER(self)

for attr_name in ['API_URL', 'SUCCESS_CODE', 'METHODS_SUCCESS_CODES']:
setattr(self.requester, attr_name, getattr(self, attr_name, None))

@property
def json_output(self):
return self.JSON_ABLE and self.client.json_output

def _arguments_get(self, varnames, vals):
"""
allows to automatically fetch values of varnames
Expand All @@ -66,6 +67,10 @@ def _arguments_get(self, varnames, vals):
>>> return self.get_file_id_from_name(vals.get('name', None))
>>>
>>> nxc.get_file_id(name='foo.bar')
:param varmames: list of wanted python var names
:param vals: a dict object containing already set variables
:returns: list of wanted values
"""
if 'kwargs' in vals:
vals.update(vals['kwargs'])
Expand Down
25 changes: 17 additions & 8 deletions src/nextcloud/common/properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ class Property(object, six.with_metaclass(MetaProperty)):
def __init__(self, xml_name, json=None, default=None, parse_xml_value=None):
if ':' in xml_name:
(self.ns, self.xml_key) = xml_name.split(':')
self._name_convention = NAMESPACES_CLASSES[self.ns]
if self.ns in NAMESPACES_CLASSES:
self._name_convention = NAMESPACES_CLASSES[self.ns]._name_convention
else:
self.xml_key = xml_name
if self.namespace:
Expand All @@ -56,16 +57,23 @@ def __init__(self, xml_name, json=None, default=None, parse_xml_value=None):
self.default_val = default
self.parse_xml_value = parse_xml_value

@classmethod
def _xml_name_to_py_name(cls, name):
if name in cls._name_convention:
return cls._name_convention[name]
def __repr__(self):
return "<{}: ns={}, xml={}, py={}, json={}>".format(
self.__class__.__name__,
self.ns,
self.attr_name,
self.xml_key,
self.json_key
)

def _xml_name_to_py_name(self, name):
if name in self._name_convention:
return self._name_convention[name]
else:
return name.replace('-', '_')

@classmethod
def _py_name_to_xml_name(cls, name):
_reversed_convention = {v: k for k, v in cls._name_convention.items()}
def _py_name_to_xml_name(self, name):
_reversed_convention = {v: k for k, v in self._name_convention.items()}
if name in _reversed_convention:
return _reversed_convention[name]
else:
Expand Down Expand Up @@ -105,6 +113,7 @@ class DProp(Property):
'getcontentlength': 'content_length'
}


class OCProp(Property):
""" OwnCloud property """
namespace = ('oc', 'http://owncloud.org/ns')
Expand Down
Loading

0 comments on commit e95e19d

Please sign in to comment.