saviialib 1.3.0__py3-none-any.whl → 1.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of saviialib might be problematic. Click here for more details.

Files changed (64) hide show
  1. saviialib/__init__.py +73 -3
  2. saviialib/general_types/api/__init__.py +0 -3
  3. saviialib/general_types/api/{epii_api_types.py → saviia_api_types.py} +2 -38
  4. saviialib/general_types/api/saviia_backup_api_types.py +24 -0
  5. saviialib/general_types/api/saviia_netcamera_api_types.py +11 -0
  6. saviialib/general_types/api/saviia_shakes_api_types.py +21 -0
  7. saviialib/general_types/api/saviia_thies_api_types.py +31 -0
  8. saviialib/general_types/error_types/api/{epii_api_error_types.py → saviia_api_error_types.py} +8 -0
  9. saviialib/general_types/error_types/api/saviia_netcamera_error_types.py +7 -0
  10. saviialib/general_types/error_types/common/common_types.py +9 -0
  11. saviialib/libs/directory_client/client/os_client.py +1 -1
  12. saviialib/libs/ffmpeg_client/__init__.py +8 -0
  13. saviialib/libs/ffmpeg_client/clients/ffmpeg_asyncio_client.py +101 -0
  14. saviialib/libs/ffmpeg_client/ffmpeg_client.py +25 -0
  15. saviialib/libs/ffmpeg_client/ffmpeg_client_contract.py +12 -0
  16. saviialib/libs/ffmpeg_client/types/ffmpeg_client_types.py +28 -0
  17. saviialib/libs/sftp_client/__init__.py +8 -0
  18. saviialib/libs/sftp_client/clients/asyncssh_sftp_client.py +83 -0
  19. saviialib/libs/sftp_client/sftp_client.py +26 -0
  20. saviialib/libs/sftp_client/sftp_client_contract.py +13 -0
  21. saviialib/libs/sftp_client/types/sftp_client_types.py +24 -0
  22. saviialib/libs/sharepoint_client/clients/sharepoint_rest_api.py +7 -3
  23. saviialib/libs/zero_dependency/utils/strings_utils.py +5 -0
  24. saviialib/services/backup/api.py +36 -0
  25. saviialib/services/{epii → backup}/controllers/types/__init__.py +1 -1
  26. saviialib/services/{epii → backup}/controllers/types/upload_backup_to_sharepoint_types.py +2 -2
  27. saviialib/services/{epii → backup}/controllers/upload_backup_to_sharepoint.py +5 -5
  28. saviialib/services/{epii → backup}/use_cases/types/__init__.py +1 -1
  29. saviialib/services/{epii → backup}/use_cases/types/upload_backup_to_sharepoint_types.py +1 -1
  30. saviialib/services/{epii → backup}/use_cases/upload_backup_to_sharepoint.py +2 -2
  31. saviialib/services/backup/utils/__init__.py +3 -0
  32. saviialib/services/{epii → backup}/utils/upload_backup_to_sharepoint_utils.py +1 -1
  33. saviialib/services/netcamera/api.py +30 -0
  34. saviialib/services/netcamera/controllers/get_media_files.py +40 -0
  35. saviialib/services/netcamera/controllers/types/get_media_files_types.py +16 -0
  36. saviialib/services/netcamera/use_cases/get_media_files.py +76 -0
  37. saviialib/services/netcamera/use_cases/types/get_media_files_types.py +18 -0
  38. saviialib/services/shakes/__init__.py +0 -0
  39. saviialib/services/shakes/api.py +31 -0
  40. saviialib/services/shakes/controllers/get_miniseed_files.py +48 -0
  41. saviialib/services/shakes/controllers/types/get_miniseed_files_types.py +16 -0
  42. saviialib/services/shakes/use_cases/get_miniseed_files.py +79 -0
  43. saviialib/services/shakes/use_cases/types/get_miniseed_files_types.py +18 -0
  44. saviialib/services/shakes/use_cases/utils/get_miniseed_files_utils.py +11 -0
  45. saviialib/services/thies/__init__.py +0 -0
  46. saviialib/services/thies/api.py +35 -0
  47. saviialib/services/{epii → thies}/controllers/types/update_thies_data_types.py +2 -4
  48. saviialib/services/{epii → thies}/controllers/update_thies_data.py +4 -4
  49. saviialib/services/{epii → thies}/use_cases/components/create_thies_statistics_file.py +11 -2
  50. saviialib/services/{epii → thies}/use_cases/types/update_thies_data_types.py +4 -1
  51. saviialib/services/{epii → thies}/use_cases/update_thies_data.py +19 -12
  52. saviialib-1.5.0.dist-info/METADATA +126 -0
  53. saviialib-1.5.0.dist-info/RECORD +87 -0
  54. {saviialib-1.3.0.dist-info → saviialib-1.5.0.dist-info}/WHEEL +1 -1
  55. saviialib/services/epii/api.py +0 -94
  56. saviialib/services/epii/utils/__init__.py +0 -3
  57. saviialib-1.3.0.dist-info/METADATA +0 -122
  58. saviialib-1.3.0.dist-info/RECORD +0 -57
  59. /saviialib/services/{epii → backup}/__init__.py +0 -0
  60. /saviialib/services/{epii → backup}/controllers/__init__.py +0 -0
  61. /saviialib/services/{epii → backup}/use_cases/constants/upload_backup_to_sharepoint_constants.py +0 -0
  62. /saviialib/services/{epii → thies}/use_cases/components/thies_bp.py +0 -0
  63. /saviialib/services/{epii → thies}/utils/update_thies_data_utils.py +0 -0
  64. {saviialib-1.3.0.dist-info → saviialib-1.5.0.dist-info/licenses}/LICENSE +0 -0
saviialib/__init__.py CHANGED
@@ -3,7 +3,77 @@ from importlib.metadata import version
3
3
 
4
4
  __version__ = version("saviialib")
5
5
 
6
- from .services.epii.api import EpiiAPI
7
- from .general_types.api.epii_api_types import EpiiAPIConfig
6
+ from .general_types.api.saviia_api_types import SaviiaAPIConfig
8
7
 
9
- __all__ = ["EpiiAPI", "EpiiAPIConfig"]
8
+ from typing import Dict, Type, Any, overload, Literal, List
9
+
10
+ from saviialib.services.backup.api import SaviiaBackupAPI
11
+ from saviialib.services.thies.api import SaviiaThiesAPI
12
+ from saviialib.general_types.api.saviia_thies_api_types import SaviiaThiesConfig
13
+ from saviialib.general_types.api.saviia_backup_api_types import SaviiaBackupConfig
14
+
15
+ __all__ = ["SaviiaAPI", "SaviiaAPIConfig"]
16
+
17
+
18
+ class SaviiaAPI:
19
+ API_REGISTRY: Dict[str, Type] = {
20
+ "thies": SaviiaThiesAPI,
21
+ "backup": SaviiaBackupAPI,
22
+ }
23
+
24
+ @overload
25
+ def get(self, name: Literal["thies"]) -> SaviiaThiesAPI: ...
26
+ @overload
27
+ def get(self, name: Literal["backup"]) -> SaviiaBackupAPI: ...
28
+
29
+ def __init__(self, config: SaviiaAPIConfig):
30
+ """
31
+ Receive a dictionary of configurations, with the same key
32
+ as those registered in API_REGISTRY.
33
+
34
+ :params configs: Dictionary of configurations for each API.
35
+
36
+ Example:
37
+ configs = {
38
+ "thies": SaviiaThiesConfig(...),
39
+ "backup": SaviiaBackupConfig(...)
40
+ }
41
+ """
42
+ self._instances: Dict[str, Any] = {}
43
+
44
+ for name, api_class in SaviiaAPI.API_REGISTRY.items():
45
+ if name == "thies":
46
+ service_config = SaviiaThiesConfig(
47
+ ftp_host=config.ftp_host,
48
+ ftp_port=config.ftp_port,
49
+ ftp_user=config.ftp_user,
50
+ ftp_password=config.ftp_password,
51
+ sharepoint_client_id=config.sharepoint_client_id,
52
+ sharepoint_client_secret=config.sharepoint_client_secret,
53
+ sharepoint_tenant_id=config.sharepoint_tenant_id,
54
+ sharepoint_tenant_name=config.sharepoint_tenant_name,
55
+ sharepoint_site_name=config.sharepoint_site_name,
56
+ logger=config.logger,
57
+ )
58
+ elif name == "backup":
59
+ service_config = SaviiaBackupConfig(
60
+ sharepoint_client_id=config.sharepoint_client_id,
61
+ sharepoint_client_secret=config.sharepoint_client_secret,
62
+ sharepoint_tenant_id=config.sharepoint_tenant_id,
63
+ sharepoint_tenant_name=config.sharepoint_tenant_name,
64
+ sharepoint_site_name=config.sharepoint_site_name,
65
+ logger=config.logger,
66
+ )
67
+
68
+ self._instances[name] = api_class(service_config)
69
+
70
+ def get(self, name: Literal["thies", "backup"]) -> Any:
71
+ """Returns the API instance associated with the given name."""
72
+ try:
73
+ return self._instances[name]
74
+ except KeyError:
75
+ raise ValueError(f"API '{name}' is not registered or not configured.")
76
+
77
+ def list_available(self) -> List[str]:
78
+ """List of available registered APIs."""
79
+ return list(self._instances.keys())
@@ -1,3 +0,0 @@
1
- from .epii_api_types import EpiiUpdateThiesConfig, EpiiSharepointBackupConfig
2
-
3
- __all__ = ["EpiiUpdateThiesConfig", "EpiiSharepointBackupConfig"]
@@ -3,9 +3,9 @@ from logging import Logger
3
3
 
4
4
 
5
5
  @dataclass
6
- class EpiiAPIConfig:
6
+ class SaviiaAPIConfig:
7
7
  """
8
- Configuration for Epii API.
8
+ Configuration for SAVIIA API.
9
9
 
10
10
  Attributes:
11
11
  ftp_port (int): Port number of the FTP server.
@@ -46,39 +46,3 @@ class SharepointConfig:
46
46
  sharepoint_tenant_id: str
47
47
  sharepoint_tenant_name: str
48
48
  sharepoint_site_name: str
49
-
50
-
51
- @dataclass
52
- class EpiiUpdateThiesConfig:
53
- ftp_port: int
54
- ftp_host: str
55
- ftp_user: str
56
- ftp_password: str
57
- sharepoint_client_id: str
58
- sharepoint_client_secret: str
59
- sharepoint_tenant_id: str
60
- sharepoint_tenant_name: str
61
- sharepoint_site_name: str
62
- logger: Logger
63
-
64
-
65
- @dataclass
66
- class EpiiSharepointBackupConfig:
67
- """
68
- Configuration for backing up files to SharePoint.
69
-
70
- Attributes:
71
- sharepoint_client_id (str): Client ID for SharePoint authentication.
72
- sharepoint_client_secret (str): Client secret for SharePoint authentication.
73
- sharepoint_tenant_id (str): Tenant ID for SharePoint authentication.
74
- sharepoint_tenant_name (str): Tenant name for SharePoint.
75
- sharepoint_site_name (str): Site name in SharePoint.
76
- local_backup_source_path (str): Local path to backup.
77
- """
78
-
79
- sharepoint_client_id: str
80
- sharepoint_client_secret: str
81
- sharepoint_tenant_id: str
82
- sharepoint_tenant_name: str
83
- sharepoint_site_name: str
84
- logger: Logger
@@ -0,0 +1,24 @@
1
+ from dataclasses import dataclass
2
+ from logging import Logger
3
+
4
+
5
+ @dataclass
6
+ class SaviiaBackupConfig:
7
+ """
8
+ Configuration for backing up files to SharePoint.
9
+
10
+ Attributes:
11
+ sharepoint_client_id (str): Client ID for SharePoint authentication.
12
+ sharepoint_client_secret (str): Client secret for SharePoint authentication.
13
+ sharepoint_tenant_id (str): Tenant ID for SharePoint authentication.
14
+ sharepoint_tenant_name (str): Tenant name for SharePoint.
15
+ sharepoint_site_name (str): Site name in SharePoint.
16
+ local_backup_source_path (str): Local path to backup.
17
+ """
18
+
19
+ sharepoint_client_id: str
20
+ sharepoint_client_secret: str
21
+ sharepoint_tenant_id: str
22
+ sharepoint_tenant_name: str
23
+ sharepoint_site_name: str
24
+ logger: Logger
@@ -0,0 +1,11 @@
1
+ from dataclasses import dataclass
2
+ from logging import Logger
3
+
4
+
5
+ @dataclass
6
+ class SaviiaNetcameraConfig:
7
+ username: str
8
+ password: str
9
+ protocol: str
10
+ logger: Logger
11
+ destination_path: str = "/"
@@ -0,0 +1,21 @@
1
+ from dataclasses import dataclass
2
+ from logging import Logger
3
+
4
+
5
+ @dataclass
6
+ class SaviiaShakesConfig:
7
+ """
8
+ Configuration for Raspberry shakes activities as Miniseed extraction, photo record and video record.
9
+
10
+ Attributes:
11
+ sftp_user (str): Username for SFTP Client connection
12
+ sftp_password (str): Password for SFTP Client connection
13
+ sftp_port (str): SFTP Server Port. Default port is 22.
14
+ ssh_key_path (str): Path to the SSH Private key for client-side authentication.
15
+ """
16
+
17
+ sftp_user: str
18
+ sftp_password: str
19
+ ssh_key_path: str
20
+ logger: Logger
21
+ sftp_port: int = 22
@@ -0,0 +1,31 @@
1
+ from dataclasses import dataclass
2
+ from logging import Logger
3
+
4
+
5
+ @dataclass
6
+ class SaviiaThiesConfig:
7
+ """
8
+ Configuration for Saviia Thies.
9
+
10
+ Attributes:
11
+ ftp_port (int): Port number of the FTP server.
12
+ ftp_host (str): Hostname or IP address of the FTP server.
13
+ ftp_user (str): Username for the FTP server.
14
+ ftp_password (str): Password for the FTP server.
15
+ sharepoint_client_id (str): Client ID for SharePoint authentication.
16
+ sharepoint_client_secret (str): Client secret for SharePoint authentication.
17
+ sharepoint_tenant_id (str): Tenant ID for SharePoint authentication.
18
+ sharepoint_tenant_name (str): Tenant name for SharePoint.
19
+ sharepoint_site_name (str): Site name in SharePoint.
20
+ """
21
+
22
+ ftp_host: str
23
+ ftp_port: int
24
+ ftp_user: str
25
+ ftp_password: str
26
+ sharepoint_client_id: str
27
+ sharepoint_client_secret: str
28
+ sharepoint_tenant_id: str
29
+ sharepoint_tenant_name: str
30
+ sharepoint_site_name: str
31
+ logger: Logger
@@ -103,3 +103,11 @@ class BackupEmptyError(Exception):
103
103
 
104
104
  def __str__(self):
105
105
  return "The local backup folder is empty. "
106
+
107
+
108
+ class ShakesNoContentError(Exception):
109
+ def __init__(self, *args):
110
+ super().__init__(*args)
111
+
112
+ def __str__(self):
113
+ return "All the miniSEED files have been downloaded and are in the local directory."
@@ -0,0 +1,7 @@
1
+ class NetcameraConnectionError(Exception):
2
+ def __init__(self, *args, reason):
3
+ super().__init__(*args, reason)
4
+ self.reason = reason
5
+
6
+ def __str__(self):
7
+ return "Netcamera Connection failed. " + self.reason.__str__()
@@ -15,3 +15,12 @@ class SharepointClientError(Exception):
15
15
  class FtpClientError(Exception):
16
16
  def __str__(self):
17
17
  return "Ftp Client initialization fails."
18
+
19
+
20
+ class SftpClientError(Exception):
21
+ def __init__(self, *args, reason):
22
+ super().__init__(*args, reason)
23
+ self.reason = reason
24
+
25
+ def __str__(self):
26
+ return "SFTP Client initialization fails." + self.reason.__str__()
@@ -19,7 +19,7 @@ class OsClient(DirectoryClientContract):
19
19
  return await asyncio.to_thread(os.listdir, path)
20
20
 
21
21
  @staticmethod
22
- async def isdir(path: str) -> list:
22
+ async def isdir(path: str) -> bool:
23
23
  return await asyncio.to_thread(os.path.isdir, path)
24
24
 
25
25
  @staticmethod
@@ -0,0 +1,8 @@
1
+ from .ffmpeg_client import (
2
+ FfmpegClient,
3
+ FfmpegClientInitArgs,
4
+ RecordPhotoArgs,
5
+ RecordVideoArgs,
6
+ )
7
+
8
+ __all__ = ["FfmpegClient", "FfmpegClientInitArgs", "RecordPhotoArgs", "RecordVideoArgs"]
@@ -0,0 +1,101 @@
1
+ from saviialib.libs.ffmpeg_client.types.ffmpeg_client_types import (
2
+ FfmpegClientInitArgs,
3
+ RecordPhotoArgs,
4
+ RecordVideoArgs,
5
+ )
6
+ from saviialib.libs.ffmpeg_client.ffmpeg_client_contract import FfmpegClientContract
7
+ from typing import List
8
+ import asyncio
9
+ import shutil
10
+
11
+ from saviialib.libs.directory_client import DirectoryClient, DirectoryClientArgs
12
+ from saviialib.libs.zero_dependency.utils.datetime_utils import today, datetime_to_str
13
+
14
+
15
+ class FfmpegAsyncioClient(FfmpegClientContract):
16
+ def __init__(self, args: FfmpegClientInitArgs) -> None:
17
+ self.dir_client = DirectoryClient(DirectoryClientArgs("os_client"))
18
+
19
+ def _setup_io_args(
20
+ self,
21
+ rtsp_user: str,
22
+ rtsp_pwd: str,
23
+ ip: str,
24
+ dest_path: str,
25
+ record_prefix: str,
26
+ record_type: str,
27
+ ):
28
+ input_arg = f"rtsp://{rtsp_user}:{rtsp_pwd}@{ip}/stream1"
29
+ output_file = (
30
+ record_prefix
31
+ + "_"
32
+ + datetime_to_str(today(), date_format="%m-%d-%Y_%H-%M-%S")
33
+ + f".{record_type}"
34
+ )
35
+ output_arg = self.dir_client.join_paths(dest_path, output_file)
36
+ return input_arg, output_arg
37
+
38
+ async def _ensure_ffmpeg_available(self):
39
+ if shutil.which("ffmpeg"):
40
+ return
41
+ install_cmd = ["apk", "add", "ffmpeg"] # Only for Home Assistant OS
42
+ process = await asyncio.create_subprocess_shell(
43
+ *install_cmd,
44
+ stdout=asyncio.subprocess.DEVNULL,
45
+ stdin=asyncio.subprocess.PIPE,
46
+ )
47
+ _, stderr = await process.communicate()
48
+ if process.returncode != 0:
49
+ raise ConnectionAbortedError("Failed to install ffmpeg: ", stderr.decode())
50
+
51
+ async def _setup_command(
52
+ self, input_arg: str, output_arg: str, extra: dict
53
+ ) -> List[str]:
54
+ await self._ensure_ffmpeg_available() # Validate ffmpeg module is installed.
55
+ cmd = ["ffmpeg", "-y", "-i", input_arg, output_arg]
56
+ for k, v in extra.values():
57
+ cmd.insert(-1, k)
58
+ cmd.insert(-1, v)
59
+ return list(map(str, cmd))
60
+
61
+ async def record_video(self, args: RecordVideoArgs):
62
+ input_arg, output_arg = self._setup_io_args(
63
+ args.rtsp_user,
64
+ args.rtsp_password,
65
+ args.ip_address,
66
+ args.destination_path,
67
+ "Video",
68
+ args.extension,
69
+ )
70
+ cmd = await self._setup_command(
71
+ input_arg, output_arg, extra={"-t": args.duration}
72
+ )
73
+ process = await asyncio.create_subprocess_exec(
74
+ *cmd, stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE
75
+ )
76
+ _, stderr = await process.communicate()
77
+ if process.returncode != 0:
78
+ raise ConnectionError(
79
+ "Unexpected error while recording the video: ", stderr.decode()
80
+ )
81
+
82
+ async def record_photo(self, args: RecordPhotoArgs):
83
+ input_arg, output_arg = self._setup_io_args(
84
+ args.rtsp_user,
85
+ args.rtsp_password,
86
+ args.ip_address,
87
+ args.destination_path,
88
+ "Photo",
89
+ args.extension,
90
+ )
91
+ cmd = await self._setup_command(
92
+ input_arg, output_arg, extra={"-frames:v": args.frames}
93
+ )
94
+ process = await asyncio.create_subprocess_exec(
95
+ *cmd, stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE
96
+ )
97
+ _, stderr = await process.communicate()
98
+ if process.returncode != 0:
99
+ raise ConnectionError(
100
+ "Unexpected error while recording the photo: ", stderr.decode()
101
+ )
@@ -0,0 +1,25 @@
1
+ from .ffmpeg_client_contract import FfmpegClientContract
2
+ from .types.ffmpeg_client_types import (
3
+ RecordPhotoArgs,
4
+ RecordVideoArgs,
5
+ FfmpegClientInitArgs,
6
+ )
7
+ from .clients.ffmpeg_asyncio_client import FfmpegAsyncioClient
8
+
9
+
10
+ class FfmpegClient(FfmpegClientContract):
11
+ CLIENTS = {"ffmpeg_asyncio"}
12
+
13
+ def __init__(self, args: FfmpegClientInitArgs) -> None:
14
+ if args.client_name not in FfmpegClient.CLIENTS:
15
+ msg = f"Unsupported client {args.client_name}"
16
+ raise KeyError(msg)
17
+ if args.client_name == "ffmpeg_asyncio":
18
+ self.client_obj = FfmpegAsyncioClient(args)
19
+ self.client_name = args.client_name
20
+
21
+ def record_photo(self, args: RecordPhotoArgs):
22
+ return self.client_obj.record_photo(args)
23
+
24
+ def record_video(self, args: RecordVideoArgs):
25
+ return self.client_obj.record_video(args)
@@ -0,0 +1,12 @@
1
+ from abc import ABC, abstractmethod
2
+ from .types.ffmpeg_client_types import RecordPhotoArgs, RecordVideoArgs
3
+
4
+
5
+ class FfmpegClientContract(ABC):
6
+ @abstractmethod
7
+ async def record_photo(self, args: RecordPhotoArgs):
8
+ pass
9
+
10
+ @abstractmethod
11
+ async def record_video(self, args: RecordVideoArgs):
12
+ pass
@@ -0,0 +1,28 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass
5
+ class FfmpegClientInitArgs:
6
+ client_name: str
7
+
8
+
9
+ @dataclass
10
+ class RecordPhotoArgs:
11
+ ip_address: str
12
+ destination_path: str
13
+ rtsp_user: str
14
+ rtsp_password: str
15
+ port: str
16
+ extension: str
17
+ frames: int
18
+
19
+
20
+ @dataclass
21
+ class RecordVideoArgs:
22
+ destination_path: str
23
+ ip_address: str
24
+ port: str
25
+ rtsp_user: str
26
+ rtsp_password: str
27
+ extension: str
28
+ duration: int
@@ -0,0 +1,8 @@
1
+ from .sftp_client import SFTPClient
2
+ from .types.sftp_client_types import (
3
+ ListfilesArgs,
4
+ DownloadfilesArgs,
5
+ SFTPClientInitArgs,
6
+ )
7
+
8
+ __all__ = ["SFTPClient", "ListfilesArgs", "DownloadfilesArgs", "SFTPClientInitArgs"]
@@ -0,0 +1,83 @@
1
+ from saviialib.libs.sftp_client.sftp_client_contract import SFTPClientContract
2
+ from saviialib.libs.sftp_client.types.sftp_client_types import (
3
+ SFTPClientInitArgs,
4
+ ListfilesArgs,
5
+ DownloadfilesArgs,
6
+ )
7
+ from typing import Optional, List, Tuple
8
+ from saviialib.general_types.error_types.common.common_types import EmptyDataError
9
+ import asyncssh # type: ignore
10
+ from saviialib.libs.directory_client import DirectoryClient, DirectoryClientArgs
11
+
12
+
13
+ class AsyncsshSFTPClient(SFTPClientContract):
14
+ def __init__(self, args: SFTPClientInitArgs) -> None:
15
+ self.host: str = args.host
16
+ self.port: int = args.port
17
+ self.username: str = args.username
18
+ self.password: Optional[str] = args.password
19
+ self.ssh_key_path: Optional[str] = args.ssh_key_path
20
+ self.dir_client = DirectoryClient(DirectoryClientArgs("os_client"))
21
+ self._validate_credentials()
22
+
23
+ def _validate_credentials(self):
24
+ if not self.password and not self.ssh_key_path:
25
+ raise EmptyDataError(
26
+ reason="At least one attribute (ssh key or password) must be provided"
27
+ )
28
+
29
+ async def _start_connection(
30
+ self,
31
+ ) -> Tuple[asyncssh.SSHClientConnection, asyncssh.SFTPClient]:
32
+ try:
33
+ ssh_connection = await asyncssh.connect(
34
+ self.host,
35
+ username=self.username,
36
+ port=self.port,
37
+ client_keys=[self.ssh_key_path],
38
+ password=self.password,
39
+ )
40
+ sftp_client = await ssh_connection.start_sftp_client()
41
+ return ssh_connection, sftp_client
42
+ except (OSError, asyncssh.Error) as exc:
43
+ raise ConnectionError("SFTP Operation failed: " + str(exc))
44
+
45
+ async def list_files(self, args: ListfilesArgs) -> List[str]:
46
+ ssh_conn, sftp_client = await self._start_connection()
47
+ async with ssh_conn:
48
+ async with sftp_client:
49
+ files = await sftp_client.listdir(args.path)
50
+ files = [f for f in files if f not in (".", "..")]
51
+ return files
52
+ await self._end_connection(ssh_conn)
53
+
54
+ async def download_files(self, args: DownloadfilesArgs) -> None:
55
+ ssh_conn, sftp_client = await self._start_connection()
56
+ if not args.destination_path or not args.source_path:
57
+ conflict_path = (
58
+ "destination path" if not args.destination_path else "source path"
59
+ )
60
+ raise ConnectionError(f"The {conflict_path} must be provided.")
61
+
62
+ download_all = len(args.files_to_download) == 0
63
+ async with ssh_conn:
64
+ async with sftp_client:
65
+ if download_all:
66
+ await sftp_client.get(
67
+ args.source_path,
68
+ args.destination_path,
69
+ recurse=True,
70
+ preserve=True,
71
+ )
72
+ else:
73
+ for filename in args.files_to_download:
74
+ source_path = self.dir_client.join_paths(
75
+ args.source_path, filename
76
+ )
77
+ dest_path = self.dir_client.join_paths(
78
+ args.destination_path, filename
79
+ )
80
+ await sftp_client.get(source_path, dest_path)
81
+
82
+ async def _end_connection(self, connection) -> None:
83
+ await connection.wait_closed()
@@ -0,0 +1,26 @@
1
+ from .sftp_client_contract import SFTPClientContract
2
+ from .types.sftp_client_types import (
3
+ SFTPClientInitArgs,
4
+ ListfilesArgs,
5
+ DownloadfilesArgs,
6
+ )
7
+ from .clients.asyncssh_sftp_client import AsyncsshSFTPClient
8
+ from typing import List
9
+
10
+
11
+ class SFTPClient(SFTPClientContract):
12
+ CLIENTS = {"asyncssh_sftp"}
13
+
14
+ def __init__(self, args: SFTPClientInitArgs) -> None:
15
+ if args.client_name not in SFTPClient.CLIENTS:
16
+ msg = f"Unsupported client {args.client_name}"
17
+ raise KeyError(msg)
18
+ if args.client_name == "asyncssh_sftp":
19
+ self.client_obj = AsyncsshSFTPClient(args)
20
+ self.client_name = args.client_name
21
+
22
+ async def list_files(self, args: ListfilesArgs) -> List[str]:
23
+ return await self.client_obj.list_files(args)
24
+
25
+ async def download_files(self, args: DownloadfilesArgs) -> None:
26
+ return await self.client_obj.download_files(args)
@@ -0,0 +1,13 @@
1
+ from .types.sftp_client_types import ListfilesArgs, DownloadfilesArgs
2
+ from abc import ABC, abstractmethod
3
+ from typing import List
4
+
5
+
6
+ class SFTPClientContract(ABC):
7
+ @abstractmethod
8
+ async def list_files(self, args: ListfilesArgs) -> List[str]:
9
+ pass
10
+
11
+ @abstractmethod
12
+ async def download_files(self, args: DownloadfilesArgs) -> None:
13
+ pass
@@ -0,0 +1,24 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Optional, List
3
+
4
+
5
+ @dataclass
6
+ class SFTPClientInitArgs:
7
+ client_name: str
8
+ password: Optional[str]
9
+ username: str
10
+ ssh_key_path: str
11
+ host: str = "localhost"
12
+ port: int = 22
13
+
14
+
15
+ @dataclass
16
+ class ListfilesArgs:
17
+ path: str
18
+
19
+
20
+ @dataclass
21
+ class DownloadfilesArgs:
22
+ source_path: str
23
+ destination_path: str
24
+ files_to_download: List[str] = field(default_factory=list)
@@ -1,7 +1,9 @@
1
1
  from typing import Any
2
2
  import json
3
- from aiohttp import ClientError, ClientSession
3
+ from aiohttp import ClientError, ClientSession, TCPConnector
4
4
  from dotenv import load_dotenv
5
+ import ssl
6
+ import certifi
5
7
 
6
8
  from saviialib.libs.sharepoint_client.sharepoint_client_contract import (
7
9
  SharepointClientContract,
@@ -15,6 +17,7 @@ from saviialib.libs.sharepoint_client.types.sharepoint_client_types import (
15
17
  )
16
18
 
17
19
  load_dotenv()
20
+ ssl_context = ssl.create_default_context(cafile=certifi.where())
18
21
 
19
22
 
20
23
  class SharepointRestAPI(SharepointClientContract):
@@ -51,7 +54,7 @@ class SharepointRestAPI(SharepointClientContract):
51
54
  "Content-Type": "application/x-www-form-urlencoded",
52
55
  }
53
56
 
54
- async with ClientSession() as session:
57
+ async with ClientSession(connector=TCPConnector(ssl=ssl_context)) as session:
55
58
  # Load access token
56
59
  response = await session.post(url, data=payload, headers=headers)
57
60
  if response.status != 200:
@@ -75,8 +78,9 @@ class SharepointRestAPI(SharepointClientContract):
75
78
  "Content-Type": "application/json",
76
79
  }
77
80
  self.base_url = f"{site_url}/sites/{self.site_name}/_api/"
81
+ connector = TCPConnector(ssl=ssl_context)
78
82
  self.session = ClientSession(
79
- headers=self.base_headers, base_url=self.base_url
83
+ headers=self.base_headers, base_url=self.base_url, connector=connector
80
84
  )
81
85
  return self
82
86
  except ClientError as error:
@@ -0,0 +1,5 @@
1
+ def are_equal(str1: str, str2: str) -> bool:
2
+ if str1.lower() == str2.lower():
3
+ return True
4
+ else:
5
+ return False