Skip to content

Commit

Permalink
ruffs Dxxx checks (#62)
Browse files Browse the repository at this point in the history
Added checks:

- D101 _Missing docstring in public class_
- D209 _Multi-line docstring closing quotes should be on a separate
line_
- D210 _No whitespaces allowed surrounding docstring text_
- D404 _First word of the docstring should not be "This"_

---------

Signed-off-by: Alexander Piskun <bigcat88@icloud.com>
  • Loading branch information
bigcat88 authored Aug 3, 2023
1 parent 9862eb0 commit 11f5da0
Show file tree
Hide file tree
Showing 24 changed files with 144 additions and 99 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ All notable changes to this project will be documented in this file.

- Switched to `hatching` as a build system, now correct install optional dependencies.
- Renamed methods, attributes that was `shadowing a Python builtins`. Enabled additional `Ruff` linters checks.
- Regroup APIs, now Users related stuff starts with `user`, file related stuff with `file`.
- Regroup APIs, now Users related stuff starts with `user`, file related stuff with `file`, UI stuff with `gui`.

## [0.0.26 - 2023-07-29]

Expand Down
2 changes: 1 addition & 1 deletion nc_py_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
ShareStatus,
ShareType,
)
from .gui_defs import GuiActionFileInfo, GuiFileActionHandlerInfo
from .integration_fastapi import (
enable_heartbeat,
nc_app,
set_enabled_handler,
set_scopes,
)
from .nextcloud import Nextcloud, NextcloudApp
from .ui_files_actions_menu import UiActionFileInfo, UiFileActionHandlerInfo
2 changes: 1 addition & 1 deletion nc_py_api/_version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
""" Version of nc_py_api."""
"""Version of nc_py_api."""

__version__ = "0.0.27.dev2"
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

@dataclass
class CfgRecord:
"""A representation of a single key-value pair returned from the `get_values` method."""

key: str
value: str

Expand All @@ -18,8 +20,8 @@ def __init__(self, raw_data: dict):
self.value = raw_data["configvalue"]


class BasicAppCfgPref:
url_suffix: str
class _BasicAppCfgPref:
_url_suffix: str

def __init__(self, session: NcSessionBasic):
self._session = session
Expand All @@ -40,7 +42,7 @@ def get_values(self, keys: list[str]) -> list[CfgRecord]:
raise ValueError("`key` parameter can not be empty")
require_capabilities("app_ecosystem_v2", self._session.capabilities)
data = {"configKeys": keys}
results = self._session.ocs(method="POST", path=f"{APP_V2_BASIC_URL}/{self.url_suffix}/get-values", json=data)
results = self._session.ocs(method="POST", path=f"{APP_V2_BASIC_URL}/{self._url_suffix}/get-values", json=data)
return [CfgRecord(i) for i in results]

def delete(self, keys: Union[str, list[str]], not_fail=True) -> None:
Expand All @@ -52,25 +54,29 @@ def delete(self, keys: Union[str, list[str]], not_fail=True) -> None:
raise ValueError("`key` parameter can not be empty")
require_capabilities("app_ecosystem_v2", self._session.capabilities)
try:
self._session.ocs(method="DELETE", path=f"{APP_V2_BASIC_URL}/{self.url_suffix}", json={"configKeys": keys})
self._session.ocs(method="DELETE", path=f"{APP_V2_BASIC_URL}/{self._url_suffix}", json={"configKeys": keys})
except NextcloudExceptionNotFound as e:
if not not_fail:
raise e from None


class PreferencesExAPI(BasicAppCfgPref):
url_suffix = "ex-app/preference"
class PreferencesExAPI(_BasicAppCfgPref):
"""User specific preferences API."""

_url_suffix = "ex-app/preference"

def set_value(self, key: str, value: str) -> None:
if not key:
raise ValueError("`key` parameter can not be empty")
require_capabilities("app_ecosystem_v2", self._session.capabilities)
params = {"configKey": key, "configValue": value}
self._session.ocs(method="POST", path=f"{APP_V2_BASIC_URL}/{self.url_suffix}", json=params)
self._session.ocs(method="POST", path=f"{APP_V2_BASIC_URL}/{self._url_suffix}", json=params)


class AppConfigExAPI(_BasicAppCfgPref):
"""Non-user(App) specific preferences API."""

class AppConfigExAPI(BasicAppCfgPref):
url_suffix = "ex-app/config"
_url_suffix = "ex-app/config"

def set_value(self, key: str, value: str, sensitive: bool = False) -> None:
if not key:
Expand All @@ -79,4 +85,4 @@ def set_value(self, key: str, value: str, sensitive: bool = False) -> None:
params: dict = {"configKey": key, "configValue": value}
if sensitive:
params["sensitive"] = True
self._session.ocs(method="POST", path=f"{APP_V2_BASIC_URL}/{self.url_suffix}", json=params)
self._session.ocs(method="POST", path=f"{APP_V2_BASIC_URL}/{self._url_suffix}", json=params)
6 changes: 4 additions & 2 deletions nc_py_api/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ def disable(self, app_name: str) -> None:
:param app_name: id of the application.
.. note:: Does not work in NextcloudApp mode, only for Nextcloud client mode."""
.. note:: Does not work in NextcloudApp mode, only for Nextcloud client mode.
"""
if not app_name:
raise ValueError("`app_name` parameter can not be empty")
self._session.ocs(method="DELETE", path=f"{ENDPOINT}/{app_name}")
Expand All @@ -47,7 +48,8 @@ def enable(self, app_name: str) -> None:
:param app_name: id of the application.
.. note:: Does not work in NextcloudApp mode, only for Nextcloud client mode."""
.. note:: Does not work in NextcloudApp mode, only for Nextcloud client mode.
"""
if not app_name:
raise ValueError("`app_name` parameter can not be empty")
self._session.ocs(method="POST", path=f"{ENDPOINT}/{app_name}")
Expand Down
4 changes: 4 additions & 0 deletions nc_py_api/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,15 @@ class ApiScope(IntEnum):


class ApiScopesStruct(TypedDict):
"""Reply of the Nextcloud App with the desired scopes."""

required: list[int]
optional: list[int]


class OCSRespond(IntEnum):
"""Special Nextcloud respond statuses for OCS calls."""

RESPOND_SERVER_ERROR = 996
RESPOND_UNAUTHORISED = 997
RESPOND_NOT_FOUND = 998
Expand Down
2 changes: 1 addition & 1 deletion nc_py_api/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@


class FilesAPI:
"""This class provides all File System functionality and File Sharing abilities."""
"""Class that encapsulates the file system and file sharing functionality."""

sharing: FilesSharingAPI
"""API for managing Files Shares"""
Expand Down
9 changes: 6 additions & 3 deletions nc_py_api/files_defs.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ def __init__(self, **kwargs):
def last_modified(self) -> datetime:
"""Time when the object was last modified.
.. note:: ETag if more preferable way to check if the object was changed."""
.. note:: ETag if more preferable way to check if the object was changed.
"""
return self._last_modified

@last_modified.setter
Expand All @@ -53,7 +54,8 @@ def last_modified(self, value: Union[str, datetime]):
class FsNode:
"""A class that represents a Nextcloud file object.
Acceptable itself as a ``path`` parameter for the most file APIs."""
Acceptable itself as a ``path`` parameter for the most file APIs.
"""

full_path: str
"""Path to the object, including the username. Does not include `dav` prefix"""
Expand Down Expand Up @@ -92,7 +94,8 @@ def __eq__(self, other):
@property
def has_extra(self) -> bool:
"""Flag indicating whether this ``FsNode`` was obtained by the `mkdir` or `upload`
methods and does not contain extended information."""
methods and does not contain extended information.
"""
return bool(self.info.permissions)

@property
Expand Down
2 changes: 1 addition & 1 deletion nc_py_api/files_sharing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


class FilesSharingAPI:
"""This class provides all File Sharing functionality."""
"""Class provides all File Sharing functionality."""

def __init__(self, session: NcSessionBasic):
self._session = session
Expand Down
16 changes: 16 additions & 0 deletions nc_py_api/gui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Nextcloud API for User Interface."""

from dataclasses import dataclass

from ._session import NcSessionApp
from .gui_files import GuiFilesActionsAPI


@dataclass
class GuiApi:
"""Class that encapsulates all UI functionality."""

files_dropdown_menu: GuiFilesActionsAPI

def __init__(self, session: NcSessionApp):
self.files_dropdown_menu = GuiFilesActionsAPI(session)
22 changes: 22 additions & 0 deletions nc_py_api/gui_defs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Definitions related to the Graphical User Interface."""
from pydantic import BaseModel


class GuiActionFileInfo(BaseModel):
"""File Information Nextcloud sends to the External Application."""

fileId: int
name: str
directory: str
etag: str
mime: str
favorite: str
permissions: int


class GuiFileActionHandlerInfo(BaseModel):
"""Action information Nextcloud sends to the External Application."""

actionName: str
actionHandler: str
actionFile: GuiActionFileInfo
24 changes: 3 additions & 21 deletions nc_py_api/ui_files_actions_menu.py → nc_py_api/gui_files.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,15 @@
"""Nextcloud API for working with drop-down file's menu."""

from pydantic import BaseModel

from ._session import NcSessionApp
from .constants import APP_V2_BASIC_URL
from .exceptions import NextcloudExceptionNotFound
from .misc import require_capabilities


class UiActionFileInfo(BaseModel):
fileId: int
name: str
directory: str
etag: str
mime: str
favorite: str
permissions: int


class UiFileActionHandlerInfo(BaseModel):
actionName: str
actionHandler: str
actionFile: UiActionFileInfo


ENDPOINT_SUFFIX = "files/actions/menu"


class UiFilesActionsAPI:
class GuiFilesActionsAPI:
"""API for the drop-down menu in Nextcloud ``Files`` app."""

def __init__(self, session: NcSessionApp):
self._session = session

Expand Down
38 changes: 21 additions & 17 deletions nc_py_api/nextcloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@
from fastapi import Request

from ._session import AppConfig, NcSession, NcSessionApp, NcSessionBasic, ServerVersion
from .appconfig_preferences_ex import AppConfigExAPI, PreferencesExAPI
from .appcfg_prefs_ex import AppConfigExAPI, PreferencesExAPI
from .apps import AppAPI
from .constants import APP_V2_BASIC_URL, ApiScope, LogLvl
from .files import FilesAPI
from .gui import GuiApi
from .misc import check_capabilities
from .preferences import PreferencesAPI
from .theming import ThemingInfo, get_parsed_theme
from .ui_files_actions_menu import UiFilesActionsAPI
from .users import UsersAPI


class NextcloudBasic(ABC):
class _NextcloudBasic(ABC):
apps: AppAPI
"""Nextcloud API for App management"""
files: FilesAPI
"""Nextcloud API for File System and Files Sharing"""
preferences_api: PreferencesAPI
preferences: PreferencesAPI
# """Nextcloud User Preferences API"""
users: UsersAPI
"""Nextcloud API for managing users, user groups, user status, user weather status"""
Expand All @@ -30,7 +30,7 @@ class NextcloudBasic(ABC):
def _init_api(self, session: NcSessionBasic):
self.apps = AppAPI(session)
self.files = FilesAPI(session)
self.preferences_api = PreferencesAPI(session)
self.preferences = PreferencesAPI(session)
self.users = UsersAPI(session)

@property
Expand All @@ -46,7 +46,8 @@ def srv_version(self) -> ServerVersion:
def check_capabilities(self, capabilities: Union[str, list[str]]) -> list[str]:
"""Returns the list with missing capabilities if any.
:param capabilities: one or more features to check for."""
:param capabilities: one or more features to check for.
"""
return check_capabilities(capabilities, self.capabilities)

def update_server_info(self) -> None:
Expand All @@ -62,10 +63,11 @@ def theme(self) -> Optional[ThemingInfo]:
return get_parsed_theme(self.capabilities["theming"]) if "theming" in self.capabilities else None


class Nextcloud(NextcloudBasic):
class Nextcloud(_NextcloudBasic):
"""Nextcloud client class.
Allows you to connect to Nextcloud and perform operations on files, shares, users, and everything else."""
Allows you to connect to Nextcloud and perform operations on files, shares, users, and everything else.
"""

_session: NcSession

Expand All @@ -80,26 +82,27 @@ def user(self) -> str:
return self._session.user


class NextcloudApp(NextcloudBasic):
class NextcloudApp(_NextcloudBasic):
"""Class for creating Nextcloud applications.
Provides additional API required for applications such as user impersonation,
endpoint registration, new authentication method, etc.
.. note:: Instance of this class should not be created directly in ``normal`` applications,
it will be provided for each app endpoint call."""
it will be provided for each app endpoint call.
"""

_session: NcSessionApp
appconfig_ex_api: AppConfigExAPI
preferences_ex_api: PreferencesExAPI
ui_files_actions: UiFilesActionsAPI
appconfig_ex: AppConfigExAPI
gui: GuiApi
preferences_ex: PreferencesExAPI

def __init__(self, **kwargs):
self._session = NcSessionApp(**kwargs)
self._init_api(self._session)
self.appconfig_ex_api = AppConfigExAPI(self._session)
self.preferences_ex_api = PreferencesExAPI(self._session)
self.ui_files_actions = UiFilesActionsAPI(self._session)
self.appconfig_ex = AppConfigExAPI(self._session)
self.preferences_ex = PreferencesExAPI(self._session)
self.gui = GuiApi(self._session)

def log(self, log_lvl: LogLvl, content: str) -> None:
"""Writes log to the Nextcloud log file.
Expand All @@ -122,7 +125,8 @@ def users_list(self) -> list[str]:
def scope_allowed(self, scope: ApiScope) -> bool:
"""Check if API scope is avalaible for application.
Useful for applications which declare ``Optional`` scopes, to check if they are allowed for them."""
Useful for applications which declare ``Optional`` scopes, to check if they are allowed for them.
"""
if self.check_capabilities("app_ecosystem_v2"):
return False
return scope in self.capabilities["app_ecosystem_v2"]["scopes"]
Expand Down
2 changes: 2 additions & 0 deletions nc_py_api/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@


class PreferencesAPI:
"""API for setting/removing configuration values of applications that support it."""

def __init__(self, session: NcSessionBasic):
self._session = session

Expand Down
4 changes: 3 additions & 1 deletion nc_py_api/users_defs.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ class WeatherLocationMode(IntEnum):

@dataclass
class WeatherLocation:
"""Class representing information about the user's location."""

latitude: float
"""Latitude in decimal degree format"""
longitude: float
Expand Down Expand Up @@ -177,7 +179,7 @@ def __init__(self, raw_info: dict):

@dataclass
class Notification:
"""A class that represents a Nextcloud Notification."""
"""Class representing information about Nextcloud notification."""

notification_id: int
"""ID of the notification."""
Expand Down
Loading

0 comments on commit 11f5da0

Please sign in to comment.