Skip to content

file_transfer_utils

This module provides methods to interact with File transfer protocols
  • FTP, SFTP, and FTPS.

FileTransferUtils

Description

| This class provides methods to interact with File transfer protocols - FTP, SFTP, and FTPS.

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
class FileTransferUtils:
    """
    Description:
        |  This class provides methods to interact with File transfer protocols
        - FTP, SFTP, and FTPS.
    """
    security = Security()

    class FTP:
        """
        Description:
            |  This class provides methods to interact with FTP.
        """

        def __init__(self):
            self.__obj_exception = CoreExceptions()
            self.logger_class = CoreLogger(name=__name__)
            self.logger = self.logger_class.get_logger()

        def open_ftp_connection(self, ftp_host: str, ftp_username: str, ftp_password: str,) -> FTP:
            """
            Establishes an FTP connection to the specified server.

            Args:
                ftp_host (str): The hostname of the FTP server.
                ftp_username (str): The username for authentication on the FTP server.
                ftp_password (str): The password for authentication on the FTP server.

            Returns:
                FTP: An FTP connection object upon successful connection.

            Raises:
                Exception: If the connection to the FTP server fails or authentication fails.

            Examples:
                >> ftp_conn = FileTransferUtils().FTP().
                open_ftp_connection('ftp.example.com', 'username', 'password')
            """
            try:
                ftp_connection = FileTransferUtils().security.open_ftp_connection(
                    ftp_host, ftp_username, ftp_password
                )
                return ftp_connection
            except error_perm as e:
                raise error_perm(f"Authentication failed: {str(e)}") from e
            except Exception as e:
                error_message = f"An unexpected error occurred: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def get_dir_info_from_ftp(self, ftp_conn: FTP, dir_path: str) -> tuple[int, dict]:
            """
            Retrieves file details like name, size, last modified date, permissions, and owner
            from an FTP directory.

            Args:
                ftp_conn (FTP): The FTP connection object.
                dir_path (str): Directory from which to retrieve file details.

            Returns:
                tuple: Number of files present in the directory and their details in a nested
                dictionary format.
            """
            try:
                file_details = {}
                ftp_conn.cwd(dir_path)  # Change to the specified directory
                file_list = []

                # Retrieve directory listing
                ftp_conn.retrlines("LIST", callback=file_list.append)

                for index, line in enumerate(file_list, start=1):
                    tokens = line.split(maxsplit=9)
                    file_details[f"file{index}"] = {
                        "file name": tokens[8],
                        "file size": tokens[4],
                        "file last modified date": str(parser.parse(" ".join(tokens[5:8]))),
                        "file permissions": tokens[0],
                        "file owner": f"{tokens[2]} {tokens[3]}"
                    }
                return len(file_details), file_details
            except Exception as e:
                error_message = f"An error occurred while connecting to the FTP server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def download_files_from_ftp(
                self, ftp_conn: FTP, files_to_download: list, ftp_dir: str, local_path: str
        ) -> None:
            """
            Downloads files from an FTP server.

            Args:
                ftp_conn (FTP): The FTP connection object.
                files_to_download (list): List of filenames to download.
                ftp_dir (str): Directory on the FTP server from which to download files.
                local_path (str): Local directory where the files will be saved.

            Examples:
                >> FileTransferUtils().FTP().download_files_from_ftp(ftp_conn,
                ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
            """
            try:
                ftp_conn.cwd(ftp_dir)
                os.makedirs(local_path, exist_ok=True)
                for file in files_to_download:
                    local_file_path = os.path.join(local_path, file)
                    with open(local_file_path, "wb") as local_file:
                        ftp_conn.retrbinary(f"RETR {file}", local_file.write, 1024)
            except Exception as e:
                error_message = f"An error occurred while downloading files from the FTP " \
                                f"server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def uploading_files_to_ftp(
                self, pobject_ftp_conn: FTP, plist_upload_files: list,
                pstr_ftp_dir: str, pstr_local_path: str
        ) -> None:
            """
            This method uploads files to FTP.

            Args:
                pobject_ftp_conn (FTP Connection Object): The FTP connection object.
                plist_upload_files (list): List of files that need to be uploaded.
                pstr_ftp_dir (str): Directory to where the files need to be uploaded.
                pstr_local_path (str): Local path from where the files need to be uploaded.

            Examples:
                >> FileTransferUtils().FTP().uploading_files_to_ftp(ftp_conn,
                ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
            """
            try:
                pobject_ftp_conn.cwd(pstr_ftp_dir)
                for file in plist_upload_files:
                    str_file_local = os.path.join(pstr_local_path, file)
                    with open(str_file_local, "rb") as local_file:
                        pobject_ftp_conn.storbinary("STOR " + file, local_file)
                    local_file.close()
            except Exception as e:
                self.__obj_exception.raise_generic_exception(str(e))
                raise e

        def close_ftp_conn(self, ftp_conn: FTP) -> None:
            """
            Closes the FTP connection.

            Args:
                ftp_conn (FTP): The FTP connection object to be closed.

            Examples:
                >> FileTransferUtils().FTP().close_ftp_conn(ftp_conn)
            """
            if ftp_conn is None:
                raise ValueError("FTP connection object cannot be None.")

            try:
                ftp_conn.quit()
            except Exception as e:
                error_message = f"Failed to close FTP connection: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

    class SFTP:
        """ This class provides methods to interact with SFTP. """

        def __init__(self):
            self.__obj_exception = CoreExceptions()
            self.logger_class = CoreLogger(name=__name__)
            self.logger = self.logger_class.get_logger()
            self.transport = None

        def open_sftp_connection(
                self, sftp_host: str, sftp_port: int, sftp_username: str,
                sftp_password: str
        ) -> paramiko.SFTPClient:
            """
            This method creates an SFTP connection.

            Args:
                sftp_host (str): Host name of the SFTP server.
                sftp_port (int): Port number for the SFTP server.
                sftp_username (str): Username for the SFTP server.
                sftp_password (str): Password for the SFTP server.

            Returns:
                SFTP Connection Object: The created SFTP connection object.

            Examples:
                >> sftp_conn = FileTransferUtils().SFTP().
                open_sftp_connection('sftp.example.com', 22, 'username', 'password')
            """
            try:

                sftp_connection, self.transport = FileTransferUtils().security.open_sftp_connection(
                    sftp_host, sftp_port, sftp_username, sftp_password
                )
                return sftp_connection
            except Exception as e:
                error_message = f"An error occurred while connecting to the SFTP server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def get_dir_info_from_sftp(self, sftp_conn: paramiko.SFTPClient,
                                   dir_path: str) -> tuple[int, dict]:
            """
            This method retrieves file details like name, size, last modified date, permissions,
             and owner from SFTP.

            Args:
                sftp_conn (SFTP Connection Object): The SFTP connection object.
                dir_path (str): Directory from where the file details need to be retrieved.

            Returns:
                tuple: Number of files present in the directory and their details in a nested
                dictionary format.

            Examples:
                >> file_count, file_details = FileTransferUtils().SFTP().
                get_dir_info_from_sftp(sftp_conn, '/Inbox/')
            """
            try:
                file_details = {}
                file_list = sftp_conn.listdir_attr(dir_path)

                for index, file_attr in enumerate(file_list, start=1):
                    file_details[f"file{index}"] = {
                        "file name": file_attr.filename,
                        "file size": file_attr.st_size,
                        "file last modified date": str(datetime.fromtimestamp(file_attr.st_mtime)),
                        "file permissions": oct(file_attr.st_mode)[-3:],
                        "file owner": f"{file_attr.st_uid} {file_attr.st_gid}"
                    }
                return len(file_details), file_details
            except Exception as e:
                error_message = f"An error occurred while retrieving directory info from " \
                                f"the SFTP server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def download_files_from_sftp(
                self, sftp_conn: paramiko.SFTPClient, download_files: list, sftp_dir: str,
                local_path: str
        ) -> None:
            """
            This method downloads files from SFTP.

            Args:
                sftp_conn (SFTP Connection Object): The SFTP connection object.
                download_files (list): List of files that need to be downloaded.
                sftp_dir (str): Directory from where the files are to be downloaded.
                local_path (str): Target path to download the files.

            Examples:
                >> FileTransferUtils().SFTP().download_files_from_sftp(sftp_conn,
                ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
            """
            try:
                os.makedirs(local_path, exist_ok=True)
                for file in download_files:
                    remote_file_path = os.path.join(sftp_dir, file)
                    local_file_path = os.path.join(local_path, file)
                    self.logger.info("Downloading from %s to %s", remote_file_path, local_file_path)
                    sftp_conn.get(remote_file_path, local_file_path)
            except Exception as e:
                error_message = f"An error occurred while downloading files from the " \
                                f"SFTP server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def uploading_files_to_sftp(
                self, sftp_conn: paramiko.SFTPClient, upload_files: list, sftp_dir: str,
                local_path: str
        ) -> None:
            """
            This method uploads files to SFTP.

            Args:
                sftp_conn (SFTP Connection Object): The SFTP connection object.
                upload_files (list): List of files that need to be uploaded.
                sftp_dir (str): Directory to where the files need to be uploaded.
                local_path (str): Local path from where the files need to be uploaded.

            Examples:
                >> FileTransferUtils().SFTP().uploading_files_to_sftp(sftp_conn,
                ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
            """
            try:
                os.makedirs(local_path, exist_ok=True)
                for file in upload_files:
                    remote_file_path = os.path.join(sftp_dir, file)
                    local_file_path = os.path.join(local_path, file)
                    self.logger.info("Uploading from %s to %s", local_file_path, remote_file_path)
                    sftp_conn.put(local_file_path, remote_file_path)
            except Exception as e:
                error_message = f"An error occurred while uploading files to the " \
                                f"SFTP server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def close_sftp_conn(self, sftp_conn: paramiko.SFTPClient) -> None:
            """
            This method closes the SFTP connection.

            Args:
                sftp_conn (SFTP Connection Object): The SFTP connection object.

            Examples:
                >> FileTransferUtils().SFTP().close_sftp_conn(sftp_conn)
            """
            try:
                sftp_conn.close()
                if self.transport is not None:
                    self.transport.close()
            except Exception as e:
                self.__obj_exception.raise_generic_exception(str(e))
                raise e

    class FTPS:
        """ This class provides methods to interact with FTPS. """

        def __init__(self):
            self.__obj_exception = CoreExceptions()
            self.logger_class = CoreLogger(name=__name__)
            self.logger = self.logger_class.get_logger()

        def open_ftps_connection(self, ftps_host: str, ftps_username: str, ftps_password: str
                                 ) -> FTP_TLS:
            """
            This method creates an FTPS connection.

            Args:
                ftps_host (str): Host name of the FTPS server.
                ftps_username (str): Username for the FTPS server.
                ftps_password (str): Password for the FTPS server.

            Returns:
                FTPS Connection Object: The created FTPS connection object.

            Examples:
                >> ftps_conn = FileTransferUtils().FTPS().
                open_ftps_connection('ftps.example.com', 'username', 'password')
            """
            try:
                ftps_conn = FileTransferUtils().security.ftps_connection(
                    ftps_host, ftps_username, ftps_password
                )
                self.logger.info("Connected to FTPS server.")
                return ftps_conn
            except Exception as e:
                error_message = f"An error occurred while connecting to the " \
                                f"FTPS server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def get_dir_info_from_ftps(self, ftps_conn: FTP_TLS, dir_path: str) -> tuple[int, dict]:
            """
            This method retrieves file details like name, size, last modified date, permissions,
             and owner from FTPS.

            Args:
                ftps_conn (FTPS Connection Object): The FTPS connection object.
                dir_path (str): Directory from where the file details need to be retrieved.

            Returns:
                tuple: Number of files present in the directory and their details in a nested
                dictionary format.

            Examples:
                >> file_count, file_details = FileTransferUtils().FTPS().
                get_dir_info_from_ftps(ftps_conn, '/Inbox/')
            """
            try:
                file_details = {}
                ftps_conn.cwd(dir_path)  # Change to the specified directory

                # Retrieve directory listing
                list_log = []
                ftps_conn.retrlines("LIST", callback=list_log.append)

                for index, line in enumerate(list_log, start=1):
                    tokens = line.split(maxsplit=9)
                    file_details[f"file{index}"] = {
                        "file name": tokens[8],
                        "file size": tokens[4],
                        "file last modified date": str(parser.parse(" ".join(tokens[5:8]))),
                        "file permissions": tokens[0],
                        "file owner": f"{tokens[2]} {tokens[3]}"
                    }
                return len(file_details), file_details
            except Exception as e:
                error_message = f"An error occurred while retrieving directory info " \
                                f"from the FTPS server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def download_files_from_ftps(
                self, ftps_conn: FTP_TLS, download_files: list, ftps_dir: str, local_path: str
        ) -> None:
            """
            This method downloads files from FTPS.

            Args:
                ftps_conn (FTPS Connection Object): The FTPS connection object.
                download_files (list): List of files that need to be downloaded.
                ftps_dir (str): Directory from where the files are to be downloaded.
                local_path (str): Target path to download the files.

            Examples:
                >> FileTransferUtils().FTPS().download_files_from_ftps(ftps_conn,
                ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
            """
            try:
                os.makedirs(local_path, exist_ok=True)
                ftps_conn.cwd(ftps_dir)
                for file in download_files:
                    local_file_path = os.path.join(local_path, file)
                    with open(local_file_path, "wb") as local_file:
                        ftps_conn.retrbinary(f"RETR {file}", local_file.write, 1024)
            except Exception as e:
                error_message = f"An error occurred while downloading files from the" \
                                f" FTPS server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def uploading_files_to_ftps(
                self, ftps_conn: FTP_TLS, upload_files: list, ftps_dir: str, local_path: str
        ) -> None:
            """
            This method uploads files to FTPS.

            Args:
                ftps_conn (FTPS Connection Object): The FTPS connection object.
                upload_files (list): List of files that need to be uploaded.
                ftps_dir (str): Directory to where the files need to be uploaded.
                local_path (str): Local path from where the files need to be uploaded.

            Examples:
                >> FileTransferUtils().FTPS().uploading_files_to_ftps(ftps_conn,
                 ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
            """
            try:
                ftps_conn.cwd(ftps_dir)
                for file in upload_files:
                    local_file_path = os.path.join(local_path, file)
                    with open(local_file_path, "rb") as local_file:
                        ftps_conn.storbinary(f"STOR {file}", local_file)
            except Exception as e:
                error_message = f"An error occurred while uploading files to the " \
                                f"FTPS server: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def close_ftps_conn(self, ftps_conn: FTP_TLS) -> None:
            """
            This method closes the FTPS connection.

            Args:
                ftps_conn (FTPS Connection Object): The FTPS connection object.

            Examples:
                >> FileTransferUtils().FTPS().close_ftps_conn(ftps_conn)
            """
            try:
                ftps_conn.quit()
            except Exception as e:
                self.__obj_exception.raise_generic_exception(str(e))
                raise e

    class AWSS3:
        """
        Description:
            |  This class provides methods to interact with AWS S3.
        """

        def __init__(self):
            self.__obj_exception = CoreExceptions()
            self.__obj_file_transfer = Security()
            self.logger_class = CoreLogger(name=__name__)
            self.logger = self.logger_class.get_logger()

        def open_aws_session(self, aws_access_key_id: str, aws_secret_access_key: str,
                             **kwargs) -> boto3.Session:
            """
            Creates an AWS session.

            Args:
                aws_access_key_id (str): Access key ID for AWS.
                aws_secret_access_key (str): Secret key for AWS.
                **kwargs: Optional parameters for session configuration.
                    - aws_session_token (str, optional): Session token for AWS (if applicable).
                    - region_name (str, optional): Name of the region to connect to.
                    - botocore_session (Botocore session, optional): Botocore session object.
                    - profile_name (str, optional): Profile name for AWS credentials.

            Returns:
                Session: The created AWS session object.

            Examples:
                >> aws_session = FileTransferUtils().AWSS3().
                open_aws_session('XXXXXX', 'XXXXX')
            """
            try:
                aws_session_token = kwargs.get("aws_session_token")
                region_name = kwargs.get("region_name")
                botocore_session = kwargs.get("botocore_session")
                profile_name = kwargs.get("profile_name")

                aws_session = self.__obj_file_transfer.open_aws_session(
                    aws_access_key_id,
                    aws_secret_access_key,
                    aws_session_token,
                    region_name,
                    botocore_session,
                    profile_name,
                )

                return aws_session
            except Exception as e:
                error_message = f"An error occurred while opening the AWS session: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def open_s3_client(self, session: boto3.Session) -> boto3.Session.client:
            """
            This method creates an S3 client object.

            Args:
                session (Session): The AWS session object.

            Returns:
                S3 Client: The created S3 client connection object.

            Examples:
                >> s3_client = FileTransferUtils().AWSS3().open_s3_client(aws_session)
            """
            try:
                s3_client = session.client("s3")
                return s3_client
            except Exception as e:
                self.__obj_exception.raise_generic_exception(str(e))
                raise e

        def s3_buckets_list(self, s3_client: boto3.Session.client) -> list:
            """
            This method retrieves a list of buckets under the AWS S3 connection.

            Args:
                s3_client (S3 Client): The AWS S3 client connection object.

            Returns:
                list: A list of bucket names under the AWS S3 connection.

            Examples:
                >> buckets = FileTransferUtils().AWSS3().s3_buckets_list(s3_client)
            """
            try:
                response = s3_client.list_buckets()
                buckets = [bucket["Name"] for bucket in response["Buckets"]]
                return buckets
            except Exception as e:
                self.__obj_exception.raise_generic_exception(str(e))
                raise e

        def read_objects_from_s3(self, client: boto3.Session.client, bucket_name: str,
                                 **kwargs) -> list:
            """
            Retrieves a list of objects or folders under the specified AWS S3 bucket.

            Args:
                client (S3.Client): The AWS S3 client connection object.
                bucket_name (str): The name of the bucket.
                **kwargs: Optional parameters for filtering objects:
                    - pstr_folder_prefix (str, optional): The prefix for folder names.
                    - pstr_file_suffix (str, optional): The suffix for file names.
                    - pstr_data_type (str, optional): Type of data to retrieve ('folder'
                     or 'objects'). Defaults to 'objects'.

            Returns:
                list: A list of folders or objects under the specified bucket.

            Examples:
                >> objects = FileTransferUtils().AWSS3().read_objects_from_s3(s3_client,
                'my_bucket', pstr_data_type='folder')
            """
            try:
                folder_prefix = kwargs.get("pstr_folder_prefix")
                file_suffix = kwargs.get("pstr_file_suffix", "")
                data_type = kwargs.get("pstr_data_type", "objects")

                if data_type == "folder":
                    _, list_folders = self.s3_folders_list(client, bucket_name,
                                                           folder_prefix=folder_prefix)
                    return list_folders
                _, list_objects, _ = self. \
                    read_content_from_s3(client, bucket_name,
                                         folder_prefix=folder_prefix,
                                         file_suffix=file_suffix)
                return list_objects
            except Exception as e:
                error_message = f"An error occurred while retrieving objects from S3: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def s3_folders_list(self, s3_client: boto3.Session.client, bucket_name: str,
                            folder_prefix: str = None) -> tuple[int, list]:
            """
            Retrieves a list of folders under the specified AWS S3 bucket.

            Args:
                s3_client (S3.Client): The AWS S3 client connection object.
                bucket_name (str): The name of the bucket.
                folder_prefix (str, optional): An optional prefix to filter the folders.

            Returns:
                tuple: A tuple containing the count of folders and a list of folder names
                under the specified bucket.

            Examples:
                >> folders_count, folders = FileTransferUtils().AWSS3().
                s3_folders_list(s3_client, 'my_bucket', 'folder/')
            """
            try:
                response = s3_client.list_objects(
                    Bucket=bucket_name,
                    Prefix=folder_prefix,
                    Delimiter="/"
                )
                s3_folders_list = []
                for content in response.get("CommonPrefixes", []):
                    s3_folders_list.append(content.get("Prefix"))

                folders_count = len(s3_folders_list)
                return folders_count, s3_folders_list
            except Exception as e:
                error_message = f"An error occurred while retrieving S3 folders: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def read_content_from_s3(self, s3_client: boto3.Session.client,
                                 bucket_name: str, folder_prefix: str = None,
                                 file_suffix: str = "") -> tuple[int, list, dict]:
            """
            Retrieves a list of objects under the specified AWS S3 bucket.

            Args:
                s3_client (S3.Client): The AWS S3 client connection object.
                bucket_name (str): The name of the bucket.
                folder_prefix (str, optional): An optional prefix to filter the objects.
                file_suffix (str, optional): An optional suffix to filter the objects.

            Returns:
                tuple: A tuple containing the count of files, a list of file names, and
                a dictionary of file details.

            Examples:
                >> file_count, objects, file_details = FileTransferUtils().
                AWSS3().read_content_from_s3(s3_client, 'my_bucket',
                 folder_prefix='folder/')
            """
            try:
                if folder_prefix:
                    response = s3_client.list_objects_v2(Bucket=bucket_name,
                                                         Prefix=folder_prefix)
                else:
                    response = s3_client.list_objects_v2(Bucket=bucket_name)

                s3_files = []
                dict_s3_file_details = {}

                for index, content in enumerate(response.get("Contents", []), start=1):
                    if content.get("Key").endswith(file_suffix):
                        s3_files.append(content.get("Key"))
                        dict_s3_file_details[f"file{index}"] = {
                            "file_name": content.get("Key"),
                            "last_modified": str(content.get("LastModified")),
                            "size": content.get("Size")
                        }

                file_count = len(s3_files)
                return file_count, s3_files, dict_s3_file_details
            except Exception as e:
                error_message = f"An error occurred while reading content from S3: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def upload_file_into_s3(
                self,
                s3_client: boto3.Session.client,
                bucket_name: str,
                src_local_file_path: str,
                tgt_s3_file_path: str = None,
        ):
            """
            Uploads a file into the specified AWS S3 bucket.

            Args:
                s3_client (S3.Client): The AWS S3 client connection object.
                bucket_name (str): The name of the S3 bucket.
                src_local_file_path (str): Local source file path.
                tgt_s3_file_path (str, optional): Target file path in S3. If not provided,
                the local file name will be used.

            Returns:
                None

            Examples:
                >> FileTransferUtils().AWSS3().upload_file_into_s3(s3_client,
                 'my_bucket', 'local_file.txt')
            """
            try:
                if tgt_s3_file_path is None:
                    tgt_s3_file_path = os.path.basename(src_local_file_path)

                self.logger.info("Beginning file upload...")
                s3_client.upload_file(
                    src_local_file_path,
                    bucket_name,
                    tgt_s3_file_path,
                )
                self.logger.info("File %s successfully uploaded to S3 as %s."
                                 , src_local_file_path, tgt_s3_file_path)

            except Exception as e:
                error_message = f"An error occurred while uploading the file to S3: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def download_file_from_s3(
                self,
                s3_client: boto3.Session.client,
                bucket_name: str,
                src_s3_file_path: str,
                tgt_local_file_path: str = None,
        ):
            """
            Downloads a file from the specified AWS S3 bucket.

            Args:
                s3_client (S3.Client): The AWS S3 client connection object.
                bucket_name (str): The name of the S3 bucket.
                src_s3_file_path (str): The source file path in S3.
                tgt_local_file_path (str, optional): Optional local target file path.
                If not provided, the file will be saved in the current working directory
                with the same name as in S3.

            Returns:
                None

            Examples:
                >> FileTransferUtils().AWSS3().download_file_from_s3(s3_client,
                'my_bucket', 's3_file.txt', 'local_file.txt')
            """
            try:
                # Use the base name of the source file if no target path is specified
                if tgt_local_file_path is None:
                    tgt_local_file_path = os.path.join(os.getcwd(),
                                                       os.path.basename(src_s3_file_path))

                self.logger.info("Beginning file download...")

                # Download the file from S3
                s3_client.download_file(
                    bucket_name,
                    src_s3_file_path,
                    tgt_local_file_path,
                )

                self.logger.info("File %s successfully downloaded to %s.", src_s3_file_path,
                                 tgt_local_file_path)

            except Exception as e:
                error_message = f"An error occurred while downloading the file " \
                                f"from S3: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def download_folder_from_s3(
                self,
                s3_client: boto3.Session.client,
                bucket_name: str,
                src_s3_folder_path: str,
                tgt_local_folder_path: str = None,
        ):
            """
            Downloads a folder and its contents from the specified AWS S3 bucket.

            Args:
                s3_client (S3.Client): The AWS S3 client connection object.
                bucket_name (str): The name of the S3 bucket.
                src_s3_folder_path (str): The source folder path in S3.
                tgt_local_folder_path (str, optional): Optional local target folder path.
                 If not provided, the folder will be created in the current
                 working directory.

            Returns:
                None

            Examples:
                >> FileTransferUtils().AWSS3().download_folder_from_s3(
                s3_client, 'my_bucket', 's3_folder/', 'local_folder/')
            """
            try:
                if tgt_local_folder_path is None:
                    tgt_local_folder_path = os.path.join(os.getcwd(),
                                                         os.path.basename(src_s3_folder_path))

                if not src_s3_folder_path.endswith("/"):
                    src_s3_folder_path += "/"

                paginator = s3_client.get_paginator("list_objects_v2")

                for result in paginator.paginate(Bucket=bucket_name,
                                                 Prefix=src_s3_folder_path):
                    for key in result.get("Contents", []):
                        rel_path = key["Key"][len(src_s3_folder_path):]
                        local_file_path = os.path.join(tgt_local_folder_path, rel_path)

                        if key["Key"].endswith("/"):
                            if not os.path.exists(local_file_path):
                                self.logger.info("Creating directory: %s", local_file_path)
                                os.makedirs(local_file_path)
                                self.logger.info("Directory %s created.", local_file_path)
                        else:
                            local_file_dir = os.path.dirname(local_file_path)
                            os.makedirs(local_file_dir, exist_ok=True)
                            self.logger.info("Beginning file download: %s", key['Key'])
                            s3_client.download_file(bucket_name, key["Key"], local_file_path)
                            self.logger.info("File %s successfully downloaded to %s.",
                                             key['Key'], local_file_path)

            except Exception as e:
                error_message = f"An error occurred while downloading the folder" \
                                f" from S3: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def upload_folder_into_s3(
                self,
                s3_client: boto3.Session.client,
                s3_bucket_name: str,
                src_local_folder_path: str,
                tgt_s3_folder_path: str = None,
        ):
            """
            Uploads a folder and its contents to the specified AWS S3 bucket.

            Args:
                s3_client (S3.Client): The AWS S3 client connection object.
                s3_bucket_name (str): The name of the S3 bucket.
                src_local_folder_path (str): Local source folder path.
                tgt_s3_folder_path (str, optional): Optional target folder path in
                S3. If not provided, the folder will be created in S3 with the same
                name as the local folder.

            Returns:
                None

            Examples:
                >> FileTransferUtils().AWSS3().upload_folder_into_s3(s3_client,
                'my_bucket', 'local_folder/', 's3_folder/')
            """
            try:
                if tgt_s3_folder_path is None:
                    tgt_s3_folder_path = pathlib.PurePath(src_local_folder_path).name

                if not tgt_s3_folder_path.endswith("/"):
                    tgt_s3_folder_path += "/"

                list_of_local_files = self.get_list_of_files_local(src_local_folder_path)

                for full_path in list_of_local_files:
                    source_full_path = full_path.replace("\\", "/")
                    relative_path = source_full_path[len(src_local_folder_path):]
                    target_full_path = os.path.join(tgt_s3_folder_path, relative_path)

                    self.logger.info("Beginning file upload from %s to %s...",
                                     source_full_path,
                                     target_full_path)
                    self.upload_file_into_s3(
                        s3_client, s3_bucket_name, source_full_path, target_full_path
                    )
                    self.logger.info("Successfully transferred file %s to S3.",
                                     source_full_path)

            except Exception as e:
                error_message = f"An error occurred while uploading the folder to S3: {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

        def get_list_of_files_local(self, local_dir_name: str) -> list:
            """
            Lists all the files in a given local directory, including files in
            subdirectories.

            Args:
                local_dir_name (str): Local directory name.

            Returns:
                list: A list of file paths under the given directory.

            Examples:
                >> files = FileTransferUtils().AWSS3().get_list_of_files_local(
                'local_directory/')
            """
            try:
                entries = os.listdir(local_dir_name)
                all_files = []

                for entry in entries:
                    full_path = os.path.join(local_dir_name, entry)
                    if os.path.isdir(full_path):
                        all_files.extend(self.get_list_of_files_local(full_path))
                    else:
                        all_files.append(full_path)

                return all_files
            except Exception as e:
                error_message = f"An error occurred while listing files in " \
                                f"the directory '{local_dir_name}': {str(e)}"
                self.__obj_exception.raise_generic_exception(error_message)
                raise e

AWSS3

Description

| This class provides methods to interact with AWS S3.

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
class AWSS3:
    """
    Description:
        |  This class provides methods to interact with AWS S3.
    """

    def __init__(self):
        self.__obj_exception = CoreExceptions()
        self.__obj_file_transfer = Security()
        self.logger_class = CoreLogger(name=__name__)
        self.logger = self.logger_class.get_logger()

    def open_aws_session(self, aws_access_key_id: str, aws_secret_access_key: str,
                         **kwargs) -> boto3.Session:
        """
        Creates an AWS session.

        Args:
            aws_access_key_id (str): Access key ID for AWS.
            aws_secret_access_key (str): Secret key for AWS.
            **kwargs: Optional parameters for session configuration.
                - aws_session_token (str, optional): Session token for AWS (if applicable).
                - region_name (str, optional): Name of the region to connect to.
                - botocore_session (Botocore session, optional): Botocore session object.
                - profile_name (str, optional): Profile name for AWS credentials.

        Returns:
            Session: The created AWS session object.

        Examples:
            >> aws_session = FileTransferUtils().AWSS3().
            open_aws_session('XXXXXX', 'XXXXX')
        """
        try:
            aws_session_token = kwargs.get("aws_session_token")
            region_name = kwargs.get("region_name")
            botocore_session = kwargs.get("botocore_session")
            profile_name = kwargs.get("profile_name")

            aws_session = self.__obj_file_transfer.open_aws_session(
                aws_access_key_id,
                aws_secret_access_key,
                aws_session_token,
                region_name,
                botocore_session,
                profile_name,
            )

            return aws_session
        except Exception as e:
            error_message = f"An error occurred while opening the AWS session: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def open_s3_client(self, session: boto3.Session) -> boto3.Session.client:
        """
        This method creates an S3 client object.

        Args:
            session (Session): The AWS session object.

        Returns:
            S3 Client: The created S3 client connection object.

        Examples:
            >> s3_client = FileTransferUtils().AWSS3().open_s3_client(aws_session)
        """
        try:
            s3_client = session.client("s3")
            return s3_client
        except Exception as e:
            self.__obj_exception.raise_generic_exception(str(e))
            raise e

    def s3_buckets_list(self, s3_client: boto3.Session.client) -> list:
        """
        This method retrieves a list of buckets under the AWS S3 connection.

        Args:
            s3_client (S3 Client): The AWS S3 client connection object.

        Returns:
            list: A list of bucket names under the AWS S3 connection.

        Examples:
            >> buckets = FileTransferUtils().AWSS3().s3_buckets_list(s3_client)
        """
        try:
            response = s3_client.list_buckets()
            buckets = [bucket["Name"] for bucket in response["Buckets"]]
            return buckets
        except Exception as e:
            self.__obj_exception.raise_generic_exception(str(e))
            raise e

    def read_objects_from_s3(self, client: boto3.Session.client, bucket_name: str,
                             **kwargs) -> list:
        """
        Retrieves a list of objects or folders under the specified AWS S3 bucket.

        Args:
            client (S3.Client): The AWS S3 client connection object.
            bucket_name (str): The name of the bucket.
            **kwargs: Optional parameters for filtering objects:
                - pstr_folder_prefix (str, optional): The prefix for folder names.
                - pstr_file_suffix (str, optional): The suffix for file names.
                - pstr_data_type (str, optional): Type of data to retrieve ('folder'
                 or 'objects'). Defaults to 'objects'.

        Returns:
            list: A list of folders or objects under the specified bucket.

        Examples:
            >> objects = FileTransferUtils().AWSS3().read_objects_from_s3(s3_client,
            'my_bucket', pstr_data_type='folder')
        """
        try:
            folder_prefix = kwargs.get("pstr_folder_prefix")
            file_suffix = kwargs.get("pstr_file_suffix", "")
            data_type = kwargs.get("pstr_data_type", "objects")

            if data_type == "folder":
                _, list_folders = self.s3_folders_list(client, bucket_name,
                                                       folder_prefix=folder_prefix)
                return list_folders
            _, list_objects, _ = self. \
                read_content_from_s3(client, bucket_name,
                                     folder_prefix=folder_prefix,
                                     file_suffix=file_suffix)
            return list_objects
        except Exception as e:
            error_message = f"An error occurred while retrieving objects from S3: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def s3_folders_list(self, s3_client: boto3.Session.client, bucket_name: str,
                        folder_prefix: str = None) -> tuple[int, list]:
        """
        Retrieves a list of folders under the specified AWS S3 bucket.

        Args:
            s3_client (S3.Client): The AWS S3 client connection object.
            bucket_name (str): The name of the bucket.
            folder_prefix (str, optional): An optional prefix to filter the folders.

        Returns:
            tuple: A tuple containing the count of folders and a list of folder names
            under the specified bucket.

        Examples:
            >> folders_count, folders = FileTransferUtils().AWSS3().
            s3_folders_list(s3_client, 'my_bucket', 'folder/')
        """
        try:
            response = s3_client.list_objects(
                Bucket=bucket_name,
                Prefix=folder_prefix,
                Delimiter="/"
            )
            s3_folders_list = []
            for content in response.get("CommonPrefixes", []):
                s3_folders_list.append(content.get("Prefix"))

            folders_count = len(s3_folders_list)
            return folders_count, s3_folders_list
        except Exception as e:
            error_message = f"An error occurred while retrieving S3 folders: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def read_content_from_s3(self, s3_client: boto3.Session.client,
                             bucket_name: str, folder_prefix: str = None,
                             file_suffix: str = "") -> tuple[int, list, dict]:
        """
        Retrieves a list of objects under the specified AWS S3 bucket.

        Args:
            s3_client (S3.Client): The AWS S3 client connection object.
            bucket_name (str): The name of the bucket.
            folder_prefix (str, optional): An optional prefix to filter the objects.
            file_suffix (str, optional): An optional suffix to filter the objects.

        Returns:
            tuple: A tuple containing the count of files, a list of file names, and
            a dictionary of file details.

        Examples:
            >> file_count, objects, file_details = FileTransferUtils().
            AWSS3().read_content_from_s3(s3_client, 'my_bucket',
             folder_prefix='folder/')
        """
        try:
            if folder_prefix:
                response = s3_client.list_objects_v2(Bucket=bucket_name,
                                                     Prefix=folder_prefix)
            else:
                response = s3_client.list_objects_v2(Bucket=bucket_name)

            s3_files = []
            dict_s3_file_details = {}

            for index, content in enumerate(response.get("Contents", []), start=1):
                if content.get("Key").endswith(file_suffix):
                    s3_files.append(content.get("Key"))
                    dict_s3_file_details[f"file{index}"] = {
                        "file_name": content.get("Key"),
                        "last_modified": str(content.get("LastModified")),
                        "size": content.get("Size")
                    }

            file_count = len(s3_files)
            return file_count, s3_files, dict_s3_file_details
        except Exception as e:
            error_message = f"An error occurred while reading content from S3: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def upload_file_into_s3(
            self,
            s3_client: boto3.Session.client,
            bucket_name: str,
            src_local_file_path: str,
            tgt_s3_file_path: str = None,
    ):
        """
        Uploads a file into the specified AWS S3 bucket.

        Args:
            s3_client (S3.Client): The AWS S3 client connection object.
            bucket_name (str): The name of the S3 bucket.
            src_local_file_path (str): Local source file path.
            tgt_s3_file_path (str, optional): Target file path in S3. If not provided,
            the local file name will be used.

        Returns:
            None

        Examples:
            >> FileTransferUtils().AWSS3().upload_file_into_s3(s3_client,
             'my_bucket', 'local_file.txt')
        """
        try:
            if tgt_s3_file_path is None:
                tgt_s3_file_path = os.path.basename(src_local_file_path)

            self.logger.info("Beginning file upload...")
            s3_client.upload_file(
                src_local_file_path,
                bucket_name,
                tgt_s3_file_path,
            )
            self.logger.info("File %s successfully uploaded to S3 as %s."
                             , src_local_file_path, tgt_s3_file_path)

        except Exception as e:
            error_message = f"An error occurred while uploading the file to S3: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def download_file_from_s3(
            self,
            s3_client: boto3.Session.client,
            bucket_name: str,
            src_s3_file_path: str,
            tgt_local_file_path: str = None,
    ):
        """
        Downloads a file from the specified AWS S3 bucket.

        Args:
            s3_client (S3.Client): The AWS S3 client connection object.
            bucket_name (str): The name of the S3 bucket.
            src_s3_file_path (str): The source file path in S3.
            tgt_local_file_path (str, optional): Optional local target file path.
            If not provided, the file will be saved in the current working directory
            with the same name as in S3.

        Returns:
            None

        Examples:
            >> FileTransferUtils().AWSS3().download_file_from_s3(s3_client,
            'my_bucket', 's3_file.txt', 'local_file.txt')
        """
        try:
            # Use the base name of the source file if no target path is specified
            if tgt_local_file_path is None:
                tgt_local_file_path = os.path.join(os.getcwd(),
                                                   os.path.basename(src_s3_file_path))

            self.logger.info("Beginning file download...")

            # Download the file from S3
            s3_client.download_file(
                bucket_name,
                src_s3_file_path,
                tgt_local_file_path,
            )

            self.logger.info("File %s successfully downloaded to %s.", src_s3_file_path,
                             tgt_local_file_path)

        except Exception as e:
            error_message = f"An error occurred while downloading the file " \
                            f"from S3: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def download_folder_from_s3(
            self,
            s3_client: boto3.Session.client,
            bucket_name: str,
            src_s3_folder_path: str,
            tgt_local_folder_path: str = None,
    ):
        """
        Downloads a folder and its contents from the specified AWS S3 bucket.

        Args:
            s3_client (S3.Client): The AWS S3 client connection object.
            bucket_name (str): The name of the S3 bucket.
            src_s3_folder_path (str): The source folder path in S3.
            tgt_local_folder_path (str, optional): Optional local target folder path.
             If not provided, the folder will be created in the current
             working directory.

        Returns:
            None

        Examples:
            >> FileTransferUtils().AWSS3().download_folder_from_s3(
            s3_client, 'my_bucket', 's3_folder/', 'local_folder/')
        """
        try:
            if tgt_local_folder_path is None:
                tgt_local_folder_path = os.path.join(os.getcwd(),
                                                     os.path.basename(src_s3_folder_path))

            if not src_s3_folder_path.endswith("/"):
                src_s3_folder_path += "/"

            paginator = s3_client.get_paginator("list_objects_v2")

            for result in paginator.paginate(Bucket=bucket_name,
                                             Prefix=src_s3_folder_path):
                for key in result.get("Contents", []):
                    rel_path = key["Key"][len(src_s3_folder_path):]
                    local_file_path = os.path.join(tgt_local_folder_path, rel_path)

                    if key["Key"].endswith("/"):
                        if not os.path.exists(local_file_path):
                            self.logger.info("Creating directory: %s", local_file_path)
                            os.makedirs(local_file_path)
                            self.logger.info("Directory %s created.", local_file_path)
                    else:
                        local_file_dir = os.path.dirname(local_file_path)
                        os.makedirs(local_file_dir, exist_ok=True)
                        self.logger.info("Beginning file download: %s", key['Key'])
                        s3_client.download_file(bucket_name, key["Key"], local_file_path)
                        self.logger.info("File %s successfully downloaded to %s.",
                                         key['Key'], local_file_path)

        except Exception as e:
            error_message = f"An error occurred while downloading the folder" \
                            f" from S3: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def upload_folder_into_s3(
            self,
            s3_client: boto3.Session.client,
            s3_bucket_name: str,
            src_local_folder_path: str,
            tgt_s3_folder_path: str = None,
    ):
        """
        Uploads a folder and its contents to the specified AWS S3 bucket.

        Args:
            s3_client (S3.Client): The AWS S3 client connection object.
            s3_bucket_name (str): The name of the S3 bucket.
            src_local_folder_path (str): Local source folder path.
            tgt_s3_folder_path (str, optional): Optional target folder path in
            S3. If not provided, the folder will be created in S3 with the same
            name as the local folder.

        Returns:
            None

        Examples:
            >> FileTransferUtils().AWSS3().upload_folder_into_s3(s3_client,
            'my_bucket', 'local_folder/', 's3_folder/')
        """
        try:
            if tgt_s3_folder_path is None:
                tgt_s3_folder_path = pathlib.PurePath(src_local_folder_path).name

            if not tgt_s3_folder_path.endswith("/"):
                tgt_s3_folder_path += "/"

            list_of_local_files = self.get_list_of_files_local(src_local_folder_path)

            for full_path in list_of_local_files:
                source_full_path = full_path.replace("\\", "/")
                relative_path = source_full_path[len(src_local_folder_path):]
                target_full_path = os.path.join(tgt_s3_folder_path, relative_path)

                self.logger.info("Beginning file upload from %s to %s...",
                                 source_full_path,
                                 target_full_path)
                self.upload_file_into_s3(
                    s3_client, s3_bucket_name, source_full_path, target_full_path
                )
                self.logger.info("Successfully transferred file %s to S3.",
                                 source_full_path)

        except Exception as e:
            error_message = f"An error occurred while uploading the folder to S3: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def get_list_of_files_local(self, local_dir_name: str) -> list:
        """
        Lists all the files in a given local directory, including files in
        subdirectories.

        Args:
            local_dir_name (str): Local directory name.

        Returns:
            list: A list of file paths under the given directory.

        Examples:
            >> files = FileTransferUtils().AWSS3().get_list_of_files_local(
            'local_directory/')
        """
        try:
            entries = os.listdir(local_dir_name)
            all_files = []

            for entry in entries:
                full_path = os.path.join(local_dir_name, entry)
                if os.path.isdir(full_path):
                    all_files.extend(self.get_list_of_files_local(full_path))
                else:
                    all_files.append(full_path)

            return all_files
        except Exception as e:
            error_message = f"An error occurred while listing files in " \
                            f"the directory '{local_dir_name}': {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

download_file_from_s3(s3_client, bucket_name, src_s3_file_path, tgt_local_file_path=None)

Downloads a file from the specified AWS S3 bucket.

Parameters:

Name Type Description Default
s3_client Client

The AWS S3 client connection object.

required
bucket_name str

The name of the S3 bucket.

required
src_s3_file_path str

The source file path in S3.

required
tgt_local_file_path str

Optional local target file path.

None

Returns:

Type Description

None

Examples:

FileTransferUtils().AWSS3().download_file_from_s3(s3_client, 'my_bucket', 's3_file.txt', 'local_file.txt')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
def download_file_from_s3(
        self,
        s3_client: boto3.Session.client,
        bucket_name: str,
        src_s3_file_path: str,
        tgt_local_file_path: str = None,
):
    """
    Downloads a file from the specified AWS S3 bucket.

    Args:
        s3_client (S3.Client): The AWS S3 client connection object.
        bucket_name (str): The name of the S3 bucket.
        src_s3_file_path (str): The source file path in S3.
        tgt_local_file_path (str, optional): Optional local target file path.
        If not provided, the file will be saved in the current working directory
        with the same name as in S3.

    Returns:
        None

    Examples:
        >> FileTransferUtils().AWSS3().download_file_from_s3(s3_client,
        'my_bucket', 's3_file.txt', 'local_file.txt')
    """
    try:
        # Use the base name of the source file if no target path is specified
        if tgt_local_file_path is None:
            tgt_local_file_path = os.path.join(os.getcwd(),
                                               os.path.basename(src_s3_file_path))

        self.logger.info("Beginning file download...")

        # Download the file from S3
        s3_client.download_file(
            bucket_name,
            src_s3_file_path,
            tgt_local_file_path,
        )

        self.logger.info("File %s successfully downloaded to %s.", src_s3_file_path,
                         tgt_local_file_path)

    except Exception as e:
        error_message = f"An error occurred while downloading the file " \
                        f"from S3: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

download_folder_from_s3(s3_client, bucket_name, src_s3_folder_path, tgt_local_folder_path=None)

Downloads a folder and its contents from the specified AWS S3 bucket.

Parameters:

Name Type Description Default
s3_client Client

The AWS S3 client connection object.

required
bucket_name str

The name of the S3 bucket.

required
src_s3_folder_path str

The source folder path in S3.

required
tgt_local_folder_path str

Optional local target folder path. If not provided, the folder will be created in the current working directory.

None

Returns:

Type Description

None

Examples:

FileTransferUtils().AWSS3().download_folder_from_s3( s3_client, 'my_bucket', 's3_folder/', 'local_folder/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
def download_folder_from_s3(
        self,
        s3_client: boto3.Session.client,
        bucket_name: str,
        src_s3_folder_path: str,
        tgt_local_folder_path: str = None,
):
    """
    Downloads a folder and its contents from the specified AWS S3 bucket.

    Args:
        s3_client (S3.Client): The AWS S3 client connection object.
        bucket_name (str): The name of the S3 bucket.
        src_s3_folder_path (str): The source folder path in S3.
        tgt_local_folder_path (str, optional): Optional local target folder path.
         If not provided, the folder will be created in the current
         working directory.

    Returns:
        None

    Examples:
        >> FileTransferUtils().AWSS3().download_folder_from_s3(
        s3_client, 'my_bucket', 's3_folder/', 'local_folder/')
    """
    try:
        if tgt_local_folder_path is None:
            tgt_local_folder_path = os.path.join(os.getcwd(),
                                                 os.path.basename(src_s3_folder_path))

        if not src_s3_folder_path.endswith("/"):
            src_s3_folder_path += "/"

        paginator = s3_client.get_paginator("list_objects_v2")

        for result in paginator.paginate(Bucket=bucket_name,
                                         Prefix=src_s3_folder_path):
            for key in result.get("Contents", []):
                rel_path = key["Key"][len(src_s3_folder_path):]
                local_file_path = os.path.join(tgt_local_folder_path, rel_path)

                if key["Key"].endswith("/"):
                    if not os.path.exists(local_file_path):
                        self.logger.info("Creating directory: %s", local_file_path)
                        os.makedirs(local_file_path)
                        self.logger.info("Directory %s created.", local_file_path)
                else:
                    local_file_dir = os.path.dirname(local_file_path)
                    os.makedirs(local_file_dir, exist_ok=True)
                    self.logger.info("Beginning file download: %s", key['Key'])
                    s3_client.download_file(bucket_name, key["Key"], local_file_path)
                    self.logger.info("File %s successfully downloaded to %s.",
                                     key['Key'], local_file_path)

    except Exception as e:
        error_message = f"An error occurred while downloading the folder" \
                        f" from S3: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

get_list_of_files_local(local_dir_name)

Lists all the files in a given local directory, including files in subdirectories.

Parameters:

Name Type Description Default
local_dir_name str

Local directory name.

required

Returns:

Name Type Description
list list

A list of file paths under the given directory.

Examples:

files = FileTransferUtils().AWSS3().get_list_of_files_local( 'local_directory/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def get_list_of_files_local(self, local_dir_name: str) -> list:
    """
    Lists all the files in a given local directory, including files in
    subdirectories.

    Args:
        local_dir_name (str): Local directory name.

    Returns:
        list: A list of file paths under the given directory.

    Examples:
        >> files = FileTransferUtils().AWSS3().get_list_of_files_local(
        'local_directory/')
    """
    try:
        entries = os.listdir(local_dir_name)
        all_files = []

        for entry in entries:
            full_path = os.path.join(local_dir_name, entry)
            if os.path.isdir(full_path):
                all_files.extend(self.get_list_of_files_local(full_path))
            else:
                all_files.append(full_path)

        return all_files
    except Exception as e:
        error_message = f"An error occurred while listing files in " \
                        f"the directory '{local_dir_name}': {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

open_aws_session(aws_access_key_id, aws_secret_access_key, **kwargs)

Creates an AWS session.

Parameters:

Name Type Description Default
aws_access_key_id str

Access key ID for AWS.

required
aws_secret_access_key str

Secret key for AWS.

required
**kwargs

Optional parameters for session configuration. - aws_session_token (str, optional): Session token for AWS (if applicable). - region_name (str, optional): Name of the region to connect to. - botocore_session (Botocore session, optional): Botocore session object. - profile_name (str, optional): Profile name for AWS credentials.

{}

Returns:

Name Type Description
Session Session

The created AWS session object.

Examples:

aws_session = FileTransferUtils().AWSS3(). open_aws_session('XXXXXX', 'XXXXX')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
def open_aws_session(self, aws_access_key_id: str, aws_secret_access_key: str,
                     **kwargs) -> boto3.Session:
    """
    Creates an AWS session.

    Args:
        aws_access_key_id (str): Access key ID for AWS.
        aws_secret_access_key (str): Secret key for AWS.
        **kwargs: Optional parameters for session configuration.
            - aws_session_token (str, optional): Session token for AWS (if applicable).
            - region_name (str, optional): Name of the region to connect to.
            - botocore_session (Botocore session, optional): Botocore session object.
            - profile_name (str, optional): Profile name for AWS credentials.

    Returns:
        Session: The created AWS session object.

    Examples:
        >> aws_session = FileTransferUtils().AWSS3().
        open_aws_session('XXXXXX', 'XXXXX')
    """
    try:
        aws_session_token = kwargs.get("aws_session_token")
        region_name = kwargs.get("region_name")
        botocore_session = kwargs.get("botocore_session")
        profile_name = kwargs.get("profile_name")

        aws_session = self.__obj_file_transfer.open_aws_session(
            aws_access_key_id,
            aws_secret_access_key,
            aws_session_token,
            region_name,
            botocore_session,
            profile_name,
        )

        return aws_session
    except Exception as e:
        error_message = f"An error occurred while opening the AWS session: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

open_s3_client(session)

This method creates an S3 client object.

Parameters:

Name Type Description Default
session Session

The AWS session object.

required

Returns:

Type Description
client

S3 Client: The created S3 client connection object.

Examples:

s3_client = FileTransferUtils().AWSS3().open_s3_client(aws_session)

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
def open_s3_client(self, session: boto3.Session) -> boto3.Session.client:
    """
    This method creates an S3 client object.

    Args:
        session (Session): The AWS session object.

    Returns:
        S3 Client: The created S3 client connection object.

    Examples:
        >> s3_client = FileTransferUtils().AWSS3().open_s3_client(aws_session)
    """
    try:
        s3_client = session.client("s3")
        return s3_client
    except Exception as e:
        self.__obj_exception.raise_generic_exception(str(e))
        raise e

read_content_from_s3(s3_client, bucket_name, folder_prefix=None, file_suffix='')

Retrieves a list of objects under the specified AWS S3 bucket.

Parameters:

Name Type Description Default
s3_client Client

The AWS S3 client connection object.

required
bucket_name str

The name of the bucket.

required
folder_prefix str

An optional prefix to filter the objects.

None
file_suffix str

An optional suffix to filter the objects.

''

Returns:

Name Type Description
tuple int

A tuple containing the count of files, a list of file names, and

list

a dictionary of file details.

Examples:

file_count, objects, file_details = FileTransferUtils(). AWSS3().read_content_from_s3(s3_client, 'my_bucket', folder_prefix='folder/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
def read_content_from_s3(self, s3_client: boto3.Session.client,
                         bucket_name: str, folder_prefix: str = None,
                         file_suffix: str = "") -> tuple[int, list, dict]:
    """
    Retrieves a list of objects under the specified AWS S3 bucket.

    Args:
        s3_client (S3.Client): The AWS S3 client connection object.
        bucket_name (str): The name of the bucket.
        folder_prefix (str, optional): An optional prefix to filter the objects.
        file_suffix (str, optional): An optional suffix to filter the objects.

    Returns:
        tuple: A tuple containing the count of files, a list of file names, and
        a dictionary of file details.

    Examples:
        >> file_count, objects, file_details = FileTransferUtils().
        AWSS3().read_content_from_s3(s3_client, 'my_bucket',
         folder_prefix='folder/')
    """
    try:
        if folder_prefix:
            response = s3_client.list_objects_v2(Bucket=bucket_name,
                                                 Prefix=folder_prefix)
        else:
            response = s3_client.list_objects_v2(Bucket=bucket_name)

        s3_files = []
        dict_s3_file_details = {}

        for index, content in enumerate(response.get("Contents", []), start=1):
            if content.get("Key").endswith(file_suffix):
                s3_files.append(content.get("Key"))
                dict_s3_file_details[f"file{index}"] = {
                    "file_name": content.get("Key"),
                    "last_modified": str(content.get("LastModified")),
                    "size": content.get("Size")
                }

        file_count = len(s3_files)
        return file_count, s3_files, dict_s3_file_details
    except Exception as e:
        error_message = f"An error occurred while reading content from S3: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

read_objects_from_s3(client, bucket_name, **kwargs)

Retrieves a list of objects or folders under the specified AWS S3 bucket.

Parameters:

Name Type Description Default
client Client

The AWS S3 client connection object.

required
bucket_name str

The name of the bucket.

required
**kwargs

Optional parameters for filtering objects: - pstr_folder_prefix (str, optional): The prefix for folder names. - pstr_file_suffix (str, optional): The suffix for file names. - pstr_data_type (str, optional): Type of data to retrieve ('folder' or 'objects'). Defaults to 'objects'.

{}

Returns:

Name Type Description
list list

A list of folders or objects under the specified bucket.

Examples:

objects = FileTransferUtils().AWSS3().read_objects_from_s3(s3_client, 'my_bucket', pstr_data_type='folder')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
def read_objects_from_s3(self, client: boto3.Session.client, bucket_name: str,
                         **kwargs) -> list:
    """
    Retrieves a list of objects or folders under the specified AWS S3 bucket.

    Args:
        client (S3.Client): The AWS S3 client connection object.
        bucket_name (str): The name of the bucket.
        **kwargs: Optional parameters for filtering objects:
            - pstr_folder_prefix (str, optional): The prefix for folder names.
            - pstr_file_suffix (str, optional): The suffix for file names.
            - pstr_data_type (str, optional): Type of data to retrieve ('folder'
             or 'objects'). Defaults to 'objects'.

    Returns:
        list: A list of folders or objects under the specified bucket.

    Examples:
        >> objects = FileTransferUtils().AWSS3().read_objects_from_s3(s3_client,
        'my_bucket', pstr_data_type='folder')
    """
    try:
        folder_prefix = kwargs.get("pstr_folder_prefix")
        file_suffix = kwargs.get("pstr_file_suffix", "")
        data_type = kwargs.get("pstr_data_type", "objects")

        if data_type == "folder":
            _, list_folders = self.s3_folders_list(client, bucket_name,
                                                   folder_prefix=folder_prefix)
            return list_folders
        _, list_objects, _ = self. \
            read_content_from_s3(client, bucket_name,
                                 folder_prefix=folder_prefix,
                                 file_suffix=file_suffix)
        return list_objects
    except Exception as e:
        error_message = f"An error occurred while retrieving objects from S3: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

s3_buckets_list(s3_client)

This method retrieves a list of buckets under the AWS S3 connection.

Parameters:

Name Type Description Default
s3_client S3 Client

The AWS S3 client connection object.

required

Returns:

Name Type Description
list list

A list of bucket names under the AWS S3 connection.

Examples:

buckets = FileTransferUtils().AWSS3().s3_buckets_list(s3_client)

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
def s3_buckets_list(self, s3_client: boto3.Session.client) -> list:
    """
    This method retrieves a list of buckets under the AWS S3 connection.

    Args:
        s3_client (S3 Client): The AWS S3 client connection object.

    Returns:
        list: A list of bucket names under the AWS S3 connection.

    Examples:
        >> buckets = FileTransferUtils().AWSS3().s3_buckets_list(s3_client)
    """
    try:
        response = s3_client.list_buckets()
        buckets = [bucket["Name"] for bucket in response["Buckets"]]
        return buckets
    except Exception as e:
        self.__obj_exception.raise_generic_exception(str(e))
        raise e

s3_folders_list(s3_client, bucket_name, folder_prefix=None)

Retrieves a list of folders under the specified AWS S3 bucket.

Parameters:

Name Type Description Default
s3_client Client

The AWS S3 client connection object.

required
bucket_name str

The name of the bucket.

required
folder_prefix str

An optional prefix to filter the folders.

None

Returns:

Name Type Description
tuple int

A tuple containing the count of folders and a list of folder names

list

under the specified bucket.

Examples:

folders_count, folders = FileTransferUtils().AWSS3(). s3_folders_list(s3_client, 'my_bucket', 'folder/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def s3_folders_list(self, s3_client: boto3.Session.client, bucket_name: str,
                    folder_prefix: str = None) -> tuple[int, list]:
    """
    Retrieves a list of folders under the specified AWS S3 bucket.

    Args:
        s3_client (S3.Client): The AWS S3 client connection object.
        bucket_name (str): The name of the bucket.
        folder_prefix (str, optional): An optional prefix to filter the folders.

    Returns:
        tuple: A tuple containing the count of folders and a list of folder names
        under the specified bucket.

    Examples:
        >> folders_count, folders = FileTransferUtils().AWSS3().
        s3_folders_list(s3_client, 'my_bucket', 'folder/')
    """
    try:
        response = s3_client.list_objects(
            Bucket=bucket_name,
            Prefix=folder_prefix,
            Delimiter="/"
        )
        s3_folders_list = []
        for content in response.get("CommonPrefixes", []):
            s3_folders_list.append(content.get("Prefix"))

        folders_count = len(s3_folders_list)
        return folders_count, s3_folders_list
    except Exception as e:
        error_message = f"An error occurred while retrieving S3 folders: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

upload_file_into_s3(s3_client, bucket_name, src_local_file_path, tgt_s3_file_path=None)

Uploads a file into the specified AWS S3 bucket.

Parameters:

Name Type Description Default
s3_client Client

The AWS S3 client connection object.

required
bucket_name str

The name of the S3 bucket.

required
src_local_file_path str

Local source file path.

required
tgt_s3_file_path str

Target file path in S3. If not provided,

None

Returns:

Type Description

None

Examples:

FileTransferUtils().AWSS3().upload_file_into_s3(s3_client, 'my_bucket', 'local_file.txt')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
def upload_file_into_s3(
        self,
        s3_client: boto3.Session.client,
        bucket_name: str,
        src_local_file_path: str,
        tgt_s3_file_path: str = None,
):
    """
    Uploads a file into the specified AWS S3 bucket.

    Args:
        s3_client (S3.Client): The AWS S3 client connection object.
        bucket_name (str): The name of the S3 bucket.
        src_local_file_path (str): Local source file path.
        tgt_s3_file_path (str, optional): Target file path in S3. If not provided,
        the local file name will be used.

    Returns:
        None

    Examples:
        >> FileTransferUtils().AWSS3().upload_file_into_s3(s3_client,
         'my_bucket', 'local_file.txt')
    """
    try:
        if tgt_s3_file_path is None:
            tgt_s3_file_path = os.path.basename(src_local_file_path)

        self.logger.info("Beginning file upload...")
        s3_client.upload_file(
            src_local_file_path,
            bucket_name,
            tgt_s3_file_path,
        )
        self.logger.info("File %s successfully uploaded to S3 as %s."
                         , src_local_file_path, tgt_s3_file_path)

    except Exception as e:
        error_message = f"An error occurred while uploading the file to S3: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

upload_folder_into_s3(s3_client, s3_bucket_name, src_local_folder_path, tgt_s3_folder_path=None)

Uploads a folder and its contents to the specified AWS S3 bucket.

Parameters:

Name Type Description Default
s3_client Client

The AWS S3 client connection object.

required
s3_bucket_name str

The name of the S3 bucket.

required
src_local_folder_path str

Local source folder path.

required
tgt_s3_folder_path str

Optional target folder path in

None

Returns:

Type Description

None

Examples:

FileTransferUtils().AWSS3().upload_folder_into_s3(s3_client, 'my_bucket', 'local_folder/', 's3_folder/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
def upload_folder_into_s3(
        self,
        s3_client: boto3.Session.client,
        s3_bucket_name: str,
        src_local_folder_path: str,
        tgt_s3_folder_path: str = None,
):
    """
    Uploads a folder and its contents to the specified AWS S3 bucket.

    Args:
        s3_client (S3.Client): The AWS S3 client connection object.
        s3_bucket_name (str): The name of the S3 bucket.
        src_local_folder_path (str): Local source folder path.
        tgt_s3_folder_path (str, optional): Optional target folder path in
        S3. If not provided, the folder will be created in S3 with the same
        name as the local folder.

    Returns:
        None

    Examples:
        >> FileTransferUtils().AWSS3().upload_folder_into_s3(s3_client,
        'my_bucket', 'local_folder/', 's3_folder/')
    """
    try:
        if tgt_s3_folder_path is None:
            tgt_s3_folder_path = pathlib.PurePath(src_local_folder_path).name

        if not tgt_s3_folder_path.endswith("/"):
            tgt_s3_folder_path += "/"

        list_of_local_files = self.get_list_of_files_local(src_local_folder_path)

        for full_path in list_of_local_files:
            source_full_path = full_path.replace("\\", "/")
            relative_path = source_full_path[len(src_local_folder_path):]
            target_full_path = os.path.join(tgt_s3_folder_path, relative_path)

            self.logger.info("Beginning file upload from %s to %s...",
                             source_full_path,
                             target_full_path)
            self.upload_file_into_s3(
                s3_client, s3_bucket_name, source_full_path, target_full_path
            )
            self.logger.info("Successfully transferred file %s to S3.",
                             source_full_path)

    except Exception as e:
        error_message = f"An error occurred while uploading the folder to S3: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

FTP

Description

| This class provides methods to interact with FTP.

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
class FTP:
    """
    Description:
        |  This class provides methods to interact with FTP.
    """

    def __init__(self):
        self.__obj_exception = CoreExceptions()
        self.logger_class = CoreLogger(name=__name__)
        self.logger = self.logger_class.get_logger()

    def open_ftp_connection(self, ftp_host: str, ftp_username: str, ftp_password: str,) -> FTP:
        """
        Establishes an FTP connection to the specified server.

        Args:
            ftp_host (str): The hostname of the FTP server.
            ftp_username (str): The username for authentication on the FTP server.
            ftp_password (str): The password for authentication on the FTP server.

        Returns:
            FTP: An FTP connection object upon successful connection.

        Raises:
            Exception: If the connection to the FTP server fails or authentication fails.

        Examples:
            >> ftp_conn = FileTransferUtils().FTP().
            open_ftp_connection('ftp.example.com', 'username', 'password')
        """
        try:
            ftp_connection = FileTransferUtils().security.open_ftp_connection(
                ftp_host, ftp_username, ftp_password
            )
            return ftp_connection
        except error_perm as e:
            raise error_perm(f"Authentication failed: {str(e)}") from e
        except Exception as e:
            error_message = f"An unexpected error occurred: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def get_dir_info_from_ftp(self, ftp_conn: FTP, dir_path: str) -> tuple[int, dict]:
        """
        Retrieves file details like name, size, last modified date, permissions, and owner
        from an FTP directory.

        Args:
            ftp_conn (FTP): The FTP connection object.
            dir_path (str): Directory from which to retrieve file details.

        Returns:
            tuple: Number of files present in the directory and their details in a nested
            dictionary format.
        """
        try:
            file_details = {}
            ftp_conn.cwd(dir_path)  # Change to the specified directory
            file_list = []

            # Retrieve directory listing
            ftp_conn.retrlines("LIST", callback=file_list.append)

            for index, line in enumerate(file_list, start=1):
                tokens = line.split(maxsplit=9)
                file_details[f"file{index}"] = {
                    "file name": tokens[8],
                    "file size": tokens[4],
                    "file last modified date": str(parser.parse(" ".join(tokens[5:8]))),
                    "file permissions": tokens[0],
                    "file owner": f"{tokens[2]} {tokens[3]}"
                }
            return len(file_details), file_details
        except Exception as e:
            error_message = f"An error occurred while connecting to the FTP server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def download_files_from_ftp(
            self, ftp_conn: FTP, files_to_download: list, ftp_dir: str, local_path: str
    ) -> None:
        """
        Downloads files from an FTP server.

        Args:
            ftp_conn (FTP): The FTP connection object.
            files_to_download (list): List of filenames to download.
            ftp_dir (str): Directory on the FTP server from which to download files.
            local_path (str): Local directory where the files will be saved.

        Examples:
            >> FileTransferUtils().FTP().download_files_from_ftp(ftp_conn,
            ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
        """
        try:
            ftp_conn.cwd(ftp_dir)
            os.makedirs(local_path, exist_ok=True)
            for file in files_to_download:
                local_file_path = os.path.join(local_path, file)
                with open(local_file_path, "wb") as local_file:
                    ftp_conn.retrbinary(f"RETR {file}", local_file.write, 1024)
        except Exception as e:
            error_message = f"An error occurred while downloading files from the FTP " \
                            f"server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def uploading_files_to_ftp(
            self, pobject_ftp_conn: FTP, plist_upload_files: list,
            pstr_ftp_dir: str, pstr_local_path: str
    ) -> None:
        """
        This method uploads files to FTP.

        Args:
            pobject_ftp_conn (FTP Connection Object): The FTP connection object.
            plist_upload_files (list): List of files that need to be uploaded.
            pstr_ftp_dir (str): Directory to where the files need to be uploaded.
            pstr_local_path (str): Local path from where the files need to be uploaded.

        Examples:
            >> FileTransferUtils().FTP().uploading_files_to_ftp(ftp_conn,
            ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
        """
        try:
            pobject_ftp_conn.cwd(pstr_ftp_dir)
            for file in plist_upload_files:
                str_file_local = os.path.join(pstr_local_path, file)
                with open(str_file_local, "rb") as local_file:
                    pobject_ftp_conn.storbinary("STOR " + file, local_file)
                local_file.close()
        except Exception as e:
            self.__obj_exception.raise_generic_exception(str(e))
            raise e

    def close_ftp_conn(self, ftp_conn: FTP) -> None:
        """
        Closes the FTP connection.

        Args:
            ftp_conn (FTP): The FTP connection object to be closed.

        Examples:
            >> FileTransferUtils().FTP().close_ftp_conn(ftp_conn)
        """
        if ftp_conn is None:
            raise ValueError("FTP connection object cannot be None.")

        try:
            ftp_conn.quit()
        except Exception as e:
            error_message = f"Failed to close FTP connection: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

close_ftp_conn(ftp_conn)

Closes the FTP connection.

Parameters:

Name Type Description Default
ftp_conn FTP

The FTP connection object to be closed.

required

Examples:

FileTransferUtils().FTP().close_ftp_conn(ftp_conn)

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def close_ftp_conn(self, ftp_conn: FTP) -> None:
    """
    Closes the FTP connection.

    Args:
        ftp_conn (FTP): The FTP connection object to be closed.

    Examples:
        >> FileTransferUtils().FTP().close_ftp_conn(ftp_conn)
    """
    if ftp_conn is None:
        raise ValueError("FTP connection object cannot be None.")

    try:
        ftp_conn.quit()
    except Exception as e:
        error_message = f"Failed to close FTP connection: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

download_files_from_ftp(ftp_conn, files_to_download, ftp_dir, local_path)

Downloads files from an FTP server.

Parameters:

Name Type Description Default
ftp_conn FTP

The FTP connection object.

required
files_to_download list

List of filenames to download.

required
ftp_dir str

Directory on the FTP server from which to download files.

required
local_path str

Local directory where the files will be saved.

required

Examples:

FileTransferUtils().FTP().download_files_from_ftp(ftp_conn, ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def download_files_from_ftp(
        self, ftp_conn: FTP, files_to_download: list, ftp_dir: str, local_path: str
) -> None:
    """
    Downloads files from an FTP server.

    Args:
        ftp_conn (FTP): The FTP connection object.
        files_to_download (list): List of filenames to download.
        ftp_dir (str): Directory on the FTP server from which to download files.
        local_path (str): Local directory where the files will be saved.

    Examples:
        >> FileTransferUtils().FTP().download_files_from_ftp(ftp_conn,
        ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
    """
    try:
        ftp_conn.cwd(ftp_dir)
        os.makedirs(local_path, exist_ok=True)
        for file in files_to_download:
            local_file_path = os.path.join(local_path, file)
            with open(local_file_path, "wb") as local_file:
                ftp_conn.retrbinary(f"RETR {file}", local_file.write, 1024)
    except Exception as e:
        error_message = f"An error occurred while downloading files from the FTP " \
                        f"server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

get_dir_info_from_ftp(ftp_conn, dir_path)

Retrieves file details like name, size, last modified date, permissions, and owner from an FTP directory.

Parameters:

Name Type Description Default
ftp_conn FTP

The FTP connection object.

required
dir_path str

Directory from which to retrieve file details.

required

Returns:

Name Type Description
tuple int

Number of files present in the directory and their details in a nested

dict

dictionary format.

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def get_dir_info_from_ftp(self, ftp_conn: FTP, dir_path: str) -> tuple[int, dict]:
    """
    Retrieves file details like name, size, last modified date, permissions, and owner
    from an FTP directory.

    Args:
        ftp_conn (FTP): The FTP connection object.
        dir_path (str): Directory from which to retrieve file details.

    Returns:
        tuple: Number of files present in the directory and their details in a nested
        dictionary format.
    """
    try:
        file_details = {}
        ftp_conn.cwd(dir_path)  # Change to the specified directory
        file_list = []

        # Retrieve directory listing
        ftp_conn.retrlines("LIST", callback=file_list.append)

        for index, line in enumerate(file_list, start=1):
            tokens = line.split(maxsplit=9)
            file_details[f"file{index}"] = {
                "file name": tokens[8],
                "file size": tokens[4],
                "file last modified date": str(parser.parse(" ".join(tokens[5:8]))),
                "file permissions": tokens[0],
                "file owner": f"{tokens[2]} {tokens[3]}"
            }
        return len(file_details), file_details
    except Exception as e:
        error_message = f"An error occurred while connecting to the FTP server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

open_ftp_connection(ftp_host, ftp_username, ftp_password)

Establishes an FTP connection to the specified server.

Parameters:

Name Type Description Default
ftp_host str

The hostname of the FTP server.

required
ftp_username str

The username for authentication on the FTP server.

required
ftp_password str

The password for authentication on the FTP server.

required

Returns:

Name Type Description
FTP FTP

An FTP connection object upon successful connection.

Raises:

Type Description
Exception

If the connection to the FTP server fails or authentication fails.

Examples:

ftp_conn = FileTransferUtils().FTP(). open_ftp_connection('ftp.example.com', 'username', 'password')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def open_ftp_connection(self, ftp_host: str, ftp_username: str, ftp_password: str,) -> FTP:
    """
    Establishes an FTP connection to the specified server.

    Args:
        ftp_host (str): The hostname of the FTP server.
        ftp_username (str): The username for authentication on the FTP server.
        ftp_password (str): The password for authentication on the FTP server.

    Returns:
        FTP: An FTP connection object upon successful connection.

    Raises:
        Exception: If the connection to the FTP server fails or authentication fails.

    Examples:
        >> ftp_conn = FileTransferUtils().FTP().
        open_ftp_connection('ftp.example.com', 'username', 'password')
    """
    try:
        ftp_connection = FileTransferUtils().security.open_ftp_connection(
            ftp_host, ftp_username, ftp_password
        )
        return ftp_connection
    except error_perm as e:
        raise error_perm(f"Authentication failed: {str(e)}") from e
    except Exception as e:
        error_message = f"An unexpected error occurred: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

uploading_files_to_ftp(pobject_ftp_conn, plist_upload_files, pstr_ftp_dir, pstr_local_path)

This method uploads files to FTP.

Parameters:

Name Type Description Default
pobject_ftp_conn FTP Connection Object

The FTP connection object.

required
plist_upload_files list

List of files that need to be uploaded.

required
pstr_ftp_dir str

Directory to where the files need to be uploaded.

required
pstr_local_path str

Local path from where the files need to be uploaded.

required

Examples:

FileTransferUtils().FTP().uploading_files_to_ftp(ftp_conn, ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def uploading_files_to_ftp(
        self, pobject_ftp_conn: FTP, plist_upload_files: list,
        pstr_ftp_dir: str, pstr_local_path: str
) -> None:
    """
    This method uploads files to FTP.

    Args:
        pobject_ftp_conn (FTP Connection Object): The FTP connection object.
        plist_upload_files (list): List of files that need to be uploaded.
        pstr_ftp_dir (str): Directory to where the files need to be uploaded.
        pstr_local_path (str): Local path from where the files need to be uploaded.

    Examples:
        >> FileTransferUtils().FTP().uploading_files_to_ftp(ftp_conn,
        ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
    """
    try:
        pobject_ftp_conn.cwd(pstr_ftp_dir)
        for file in plist_upload_files:
            str_file_local = os.path.join(pstr_local_path, file)
            with open(str_file_local, "rb") as local_file:
                pobject_ftp_conn.storbinary("STOR " + file, local_file)
            local_file.close()
    except Exception as e:
        self.__obj_exception.raise_generic_exception(str(e))
        raise e

FTPS

This class provides methods to interact with FTPS.

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
class FTPS:
    """ This class provides methods to interact with FTPS. """

    def __init__(self):
        self.__obj_exception = CoreExceptions()
        self.logger_class = CoreLogger(name=__name__)
        self.logger = self.logger_class.get_logger()

    def open_ftps_connection(self, ftps_host: str, ftps_username: str, ftps_password: str
                             ) -> FTP_TLS:
        """
        This method creates an FTPS connection.

        Args:
            ftps_host (str): Host name of the FTPS server.
            ftps_username (str): Username for the FTPS server.
            ftps_password (str): Password for the FTPS server.

        Returns:
            FTPS Connection Object: The created FTPS connection object.

        Examples:
            >> ftps_conn = FileTransferUtils().FTPS().
            open_ftps_connection('ftps.example.com', 'username', 'password')
        """
        try:
            ftps_conn = FileTransferUtils().security.ftps_connection(
                ftps_host, ftps_username, ftps_password
            )
            self.logger.info("Connected to FTPS server.")
            return ftps_conn
        except Exception as e:
            error_message = f"An error occurred while connecting to the " \
                            f"FTPS server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def get_dir_info_from_ftps(self, ftps_conn: FTP_TLS, dir_path: str) -> tuple[int, dict]:
        """
        This method retrieves file details like name, size, last modified date, permissions,
         and owner from FTPS.

        Args:
            ftps_conn (FTPS Connection Object): The FTPS connection object.
            dir_path (str): Directory from where the file details need to be retrieved.

        Returns:
            tuple: Number of files present in the directory and their details in a nested
            dictionary format.

        Examples:
            >> file_count, file_details = FileTransferUtils().FTPS().
            get_dir_info_from_ftps(ftps_conn, '/Inbox/')
        """
        try:
            file_details = {}
            ftps_conn.cwd(dir_path)  # Change to the specified directory

            # Retrieve directory listing
            list_log = []
            ftps_conn.retrlines("LIST", callback=list_log.append)

            for index, line in enumerate(list_log, start=1):
                tokens = line.split(maxsplit=9)
                file_details[f"file{index}"] = {
                    "file name": tokens[8],
                    "file size": tokens[4],
                    "file last modified date": str(parser.parse(" ".join(tokens[5:8]))),
                    "file permissions": tokens[0],
                    "file owner": f"{tokens[2]} {tokens[3]}"
                }
            return len(file_details), file_details
        except Exception as e:
            error_message = f"An error occurred while retrieving directory info " \
                            f"from the FTPS server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def download_files_from_ftps(
            self, ftps_conn: FTP_TLS, download_files: list, ftps_dir: str, local_path: str
    ) -> None:
        """
        This method downloads files from FTPS.

        Args:
            ftps_conn (FTPS Connection Object): The FTPS connection object.
            download_files (list): List of files that need to be downloaded.
            ftps_dir (str): Directory from where the files are to be downloaded.
            local_path (str): Target path to download the files.

        Examples:
            >> FileTransferUtils().FTPS().download_files_from_ftps(ftps_conn,
            ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
        """
        try:
            os.makedirs(local_path, exist_ok=True)
            ftps_conn.cwd(ftps_dir)
            for file in download_files:
                local_file_path = os.path.join(local_path, file)
                with open(local_file_path, "wb") as local_file:
                    ftps_conn.retrbinary(f"RETR {file}", local_file.write, 1024)
        except Exception as e:
            error_message = f"An error occurred while downloading files from the" \
                            f" FTPS server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def uploading_files_to_ftps(
            self, ftps_conn: FTP_TLS, upload_files: list, ftps_dir: str, local_path: str
    ) -> None:
        """
        This method uploads files to FTPS.

        Args:
            ftps_conn (FTPS Connection Object): The FTPS connection object.
            upload_files (list): List of files that need to be uploaded.
            ftps_dir (str): Directory to where the files need to be uploaded.
            local_path (str): Local path from where the files need to be uploaded.

        Examples:
            >> FileTransferUtils().FTPS().uploading_files_to_ftps(ftps_conn,
             ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
        """
        try:
            ftps_conn.cwd(ftps_dir)
            for file in upload_files:
                local_file_path = os.path.join(local_path, file)
                with open(local_file_path, "rb") as local_file:
                    ftps_conn.storbinary(f"STOR {file}", local_file)
        except Exception as e:
            error_message = f"An error occurred while uploading files to the " \
                            f"FTPS server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def close_ftps_conn(self, ftps_conn: FTP_TLS) -> None:
        """
        This method closes the FTPS connection.

        Args:
            ftps_conn (FTPS Connection Object): The FTPS connection object.

        Examples:
            >> FileTransferUtils().FTPS().close_ftps_conn(ftps_conn)
        """
        try:
            ftps_conn.quit()
        except Exception as e:
            self.__obj_exception.raise_generic_exception(str(e))
            raise e

close_ftps_conn(ftps_conn)

This method closes the FTPS connection.

Parameters:

Name Type Description Default
ftps_conn FTPS Connection Object

The FTPS connection object.

required

Examples:

FileTransferUtils().FTPS().close_ftps_conn(ftps_conn)

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def close_ftps_conn(self, ftps_conn: FTP_TLS) -> None:
    """
    This method closes the FTPS connection.

    Args:
        ftps_conn (FTPS Connection Object): The FTPS connection object.

    Examples:
        >> FileTransferUtils().FTPS().close_ftps_conn(ftps_conn)
    """
    try:
        ftps_conn.quit()
    except Exception as e:
        self.__obj_exception.raise_generic_exception(str(e))
        raise e

download_files_from_ftps(ftps_conn, download_files, ftps_dir, local_path)

This method downloads files from FTPS.

Parameters:

Name Type Description Default
ftps_conn FTPS Connection Object

The FTPS connection object.

required
download_files list

List of files that need to be downloaded.

required
ftps_dir str

Directory from where the files are to be downloaded.

required
local_path str

Target path to download the files.

required

Examples:

FileTransferUtils().FTPS().download_files_from_ftps(ftps_conn, ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def download_files_from_ftps(
        self, ftps_conn: FTP_TLS, download_files: list, ftps_dir: str, local_path: str
) -> None:
    """
    This method downloads files from FTPS.

    Args:
        ftps_conn (FTPS Connection Object): The FTPS connection object.
        download_files (list): List of files that need to be downloaded.
        ftps_dir (str): Directory from where the files are to be downloaded.
        local_path (str): Target path to download the files.

    Examples:
        >> FileTransferUtils().FTPS().download_files_from_ftps(ftps_conn,
        ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
    """
    try:
        os.makedirs(local_path, exist_ok=True)
        ftps_conn.cwd(ftps_dir)
        for file in download_files:
            local_file_path = os.path.join(local_path, file)
            with open(local_file_path, "wb") as local_file:
                ftps_conn.retrbinary(f"RETR {file}", local_file.write, 1024)
    except Exception as e:
        error_message = f"An error occurred while downloading files from the" \
                        f" FTPS server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

get_dir_info_from_ftps(ftps_conn, dir_path)

This method retrieves file details like name, size, last modified date, permissions, and owner from FTPS.

Parameters:

Name Type Description Default
ftps_conn FTPS Connection Object

The FTPS connection object.

required
dir_path str

Directory from where the file details need to be retrieved.

required

Returns:

Name Type Description
tuple int

Number of files present in the directory and their details in a nested

dict

dictionary format.

Examples:

file_count, file_details = FileTransferUtils().FTPS(). get_dir_info_from_ftps(ftps_conn, '/Inbox/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def get_dir_info_from_ftps(self, ftps_conn: FTP_TLS, dir_path: str) -> tuple[int, dict]:
    """
    This method retrieves file details like name, size, last modified date, permissions,
     and owner from FTPS.

    Args:
        ftps_conn (FTPS Connection Object): The FTPS connection object.
        dir_path (str): Directory from where the file details need to be retrieved.

    Returns:
        tuple: Number of files present in the directory and their details in a nested
        dictionary format.

    Examples:
        >> file_count, file_details = FileTransferUtils().FTPS().
        get_dir_info_from_ftps(ftps_conn, '/Inbox/')
    """
    try:
        file_details = {}
        ftps_conn.cwd(dir_path)  # Change to the specified directory

        # Retrieve directory listing
        list_log = []
        ftps_conn.retrlines("LIST", callback=list_log.append)

        for index, line in enumerate(list_log, start=1):
            tokens = line.split(maxsplit=9)
            file_details[f"file{index}"] = {
                "file name": tokens[8],
                "file size": tokens[4],
                "file last modified date": str(parser.parse(" ".join(tokens[5:8]))),
                "file permissions": tokens[0],
                "file owner": f"{tokens[2]} {tokens[3]}"
            }
        return len(file_details), file_details
    except Exception as e:
        error_message = f"An error occurred while retrieving directory info " \
                        f"from the FTPS server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

open_ftps_connection(ftps_host, ftps_username, ftps_password)

This method creates an FTPS connection.

Parameters:

Name Type Description Default
ftps_host str

Host name of the FTPS server.

required
ftps_username str

Username for the FTPS server.

required
ftps_password str

Password for the FTPS server.

required

Returns:

Type Description
FTP_TLS

FTPS Connection Object: The created FTPS connection object.

Examples:

ftps_conn = FileTransferUtils().FTPS(). open_ftps_connection('ftps.example.com', 'username', 'password')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def open_ftps_connection(self, ftps_host: str, ftps_username: str, ftps_password: str
                         ) -> FTP_TLS:
    """
    This method creates an FTPS connection.

    Args:
        ftps_host (str): Host name of the FTPS server.
        ftps_username (str): Username for the FTPS server.
        ftps_password (str): Password for the FTPS server.

    Returns:
        FTPS Connection Object: The created FTPS connection object.

    Examples:
        >> ftps_conn = FileTransferUtils().FTPS().
        open_ftps_connection('ftps.example.com', 'username', 'password')
    """
    try:
        ftps_conn = FileTransferUtils().security.ftps_connection(
            ftps_host, ftps_username, ftps_password
        )
        self.logger.info("Connected to FTPS server.")
        return ftps_conn
    except Exception as e:
        error_message = f"An error occurred while connecting to the " \
                        f"FTPS server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

uploading_files_to_ftps(ftps_conn, upload_files, ftps_dir, local_path)

This method uploads files to FTPS.

Parameters:

Name Type Description Default
ftps_conn FTPS Connection Object

The FTPS connection object.

required
upload_files list

List of files that need to be uploaded.

required
ftps_dir str

Directory to where the files need to be uploaded.

required
local_path str

Local path from where the files need to be uploaded.

required

Examples:

FileTransferUtils().FTPS().uploading_files_to_ftps(ftps_conn, ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def uploading_files_to_ftps(
        self, ftps_conn: FTP_TLS, upload_files: list, ftps_dir: str, local_path: str
) -> None:
    """
    This method uploads files to FTPS.

    Args:
        ftps_conn (FTPS Connection Object): The FTPS connection object.
        upload_files (list): List of files that need to be uploaded.
        ftps_dir (str): Directory to where the files need to be uploaded.
        local_path (str): Local path from where the files need to be uploaded.

    Examples:
        >> FileTransferUtils().FTPS().uploading_files_to_ftps(ftps_conn,
         ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
    """
    try:
        ftps_conn.cwd(ftps_dir)
        for file in upload_files:
            local_file_path = os.path.join(local_path, file)
            with open(local_file_path, "rb") as local_file:
                ftps_conn.storbinary(f"STOR {file}", local_file)
    except Exception as e:
        error_message = f"An error occurred while uploading files to the " \
                        f"FTPS server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

SFTP

This class provides methods to interact with SFTP.

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
class SFTP:
    """ This class provides methods to interact with SFTP. """

    def __init__(self):
        self.__obj_exception = CoreExceptions()
        self.logger_class = CoreLogger(name=__name__)
        self.logger = self.logger_class.get_logger()
        self.transport = None

    def open_sftp_connection(
            self, sftp_host: str, sftp_port: int, sftp_username: str,
            sftp_password: str
    ) -> paramiko.SFTPClient:
        """
        This method creates an SFTP connection.

        Args:
            sftp_host (str): Host name of the SFTP server.
            sftp_port (int): Port number for the SFTP server.
            sftp_username (str): Username for the SFTP server.
            sftp_password (str): Password for the SFTP server.

        Returns:
            SFTP Connection Object: The created SFTP connection object.

        Examples:
            >> sftp_conn = FileTransferUtils().SFTP().
            open_sftp_connection('sftp.example.com', 22, 'username', 'password')
        """
        try:

            sftp_connection, self.transport = FileTransferUtils().security.open_sftp_connection(
                sftp_host, sftp_port, sftp_username, sftp_password
            )
            return sftp_connection
        except Exception as e:
            error_message = f"An error occurred while connecting to the SFTP server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def get_dir_info_from_sftp(self, sftp_conn: paramiko.SFTPClient,
                               dir_path: str) -> tuple[int, dict]:
        """
        This method retrieves file details like name, size, last modified date, permissions,
         and owner from SFTP.

        Args:
            sftp_conn (SFTP Connection Object): The SFTP connection object.
            dir_path (str): Directory from where the file details need to be retrieved.

        Returns:
            tuple: Number of files present in the directory and their details in a nested
            dictionary format.

        Examples:
            >> file_count, file_details = FileTransferUtils().SFTP().
            get_dir_info_from_sftp(sftp_conn, '/Inbox/')
        """
        try:
            file_details = {}
            file_list = sftp_conn.listdir_attr(dir_path)

            for index, file_attr in enumerate(file_list, start=1):
                file_details[f"file{index}"] = {
                    "file name": file_attr.filename,
                    "file size": file_attr.st_size,
                    "file last modified date": str(datetime.fromtimestamp(file_attr.st_mtime)),
                    "file permissions": oct(file_attr.st_mode)[-3:],
                    "file owner": f"{file_attr.st_uid} {file_attr.st_gid}"
                }
            return len(file_details), file_details
        except Exception as e:
            error_message = f"An error occurred while retrieving directory info from " \
                            f"the SFTP server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def download_files_from_sftp(
            self, sftp_conn: paramiko.SFTPClient, download_files: list, sftp_dir: str,
            local_path: str
    ) -> None:
        """
        This method downloads files from SFTP.

        Args:
            sftp_conn (SFTP Connection Object): The SFTP connection object.
            download_files (list): List of files that need to be downloaded.
            sftp_dir (str): Directory from where the files are to be downloaded.
            local_path (str): Target path to download the files.

        Examples:
            >> FileTransferUtils().SFTP().download_files_from_sftp(sftp_conn,
            ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
        """
        try:
            os.makedirs(local_path, exist_ok=True)
            for file in download_files:
                remote_file_path = os.path.join(sftp_dir, file)
                local_file_path = os.path.join(local_path, file)
                self.logger.info("Downloading from %s to %s", remote_file_path, local_file_path)
                sftp_conn.get(remote_file_path, local_file_path)
        except Exception as e:
            error_message = f"An error occurred while downloading files from the " \
                            f"SFTP server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def uploading_files_to_sftp(
            self, sftp_conn: paramiko.SFTPClient, upload_files: list, sftp_dir: str,
            local_path: str
    ) -> None:
        """
        This method uploads files to SFTP.

        Args:
            sftp_conn (SFTP Connection Object): The SFTP connection object.
            upload_files (list): List of files that need to be uploaded.
            sftp_dir (str): Directory to where the files need to be uploaded.
            local_path (str): Local path from where the files need to be uploaded.

        Examples:
            >> FileTransferUtils().SFTP().uploading_files_to_sftp(sftp_conn,
            ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
        """
        try:
            os.makedirs(local_path, exist_ok=True)
            for file in upload_files:
                remote_file_path = os.path.join(sftp_dir, file)
                local_file_path = os.path.join(local_path, file)
                self.logger.info("Uploading from %s to %s", local_file_path, remote_file_path)
                sftp_conn.put(local_file_path, remote_file_path)
        except Exception as e:
            error_message = f"An error occurred while uploading files to the " \
                            f"SFTP server: {str(e)}"
            self.__obj_exception.raise_generic_exception(error_message)
            raise e

    def close_sftp_conn(self, sftp_conn: paramiko.SFTPClient) -> None:
        """
        This method closes the SFTP connection.

        Args:
            sftp_conn (SFTP Connection Object): The SFTP connection object.

        Examples:
            >> FileTransferUtils().SFTP().close_sftp_conn(sftp_conn)
        """
        try:
            sftp_conn.close()
            if self.transport is not None:
                self.transport.close()
        except Exception as e:
            self.__obj_exception.raise_generic_exception(str(e))
            raise e

close_sftp_conn(sftp_conn)

This method closes the SFTP connection.

Parameters:

Name Type Description Default
sftp_conn SFTP Connection Object

The SFTP connection object.

required

Examples:

FileTransferUtils().SFTP().close_sftp_conn(sftp_conn)

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def close_sftp_conn(self, sftp_conn: paramiko.SFTPClient) -> None:
    """
    This method closes the SFTP connection.

    Args:
        sftp_conn (SFTP Connection Object): The SFTP connection object.

    Examples:
        >> FileTransferUtils().SFTP().close_sftp_conn(sftp_conn)
    """
    try:
        sftp_conn.close()
        if self.transport is not None:
            self.transport.close()
    except Exception as e:
        self.__obj_exception.raise_generic_exception(str(e))
        raise e

download_files_from_sftp(sftp_conn, download_files, sftp_dir, local_path)

This method downloads files from SFTP.

Parameters:

Name Type Description Default
sftp_conn SFTP Connection Object

The SFTP connection object.

required
download_files list

List of files that need to be downloaded.

required
sftp_dir str

Directory from where the files are to be downloaded.

required
local_path str

Target path to download the files.

required

Examples:

FileTransferUtils().SFTP().download_files_from_sftp(sftp_conn, ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def download_files_from_sftp(
        self, sftp_conn: paramiko.SFTPClient, download_files: list, sftp_dir: str,
        local_path: str
) -> None:
    """
    This method downloads files from SFTP.

    Args:
        sftp_conn (SFTP Connection Object): The SFTP connection object.
        download_files (list): List of files that need to be downloaded.
        sftp_dir (str): Directory from where the files are to be downloaded.
        local_path (str): Target path to download the files.

    Examples:
        >> FileTransferUtils().SFTP().download_files_from_sftp(sftp_conn,
        ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
    """
    try:
        os.makedirs(local_path, exist_ok=True)
        for file in download_files:
            remote_file_path = os.path.join(sftp_dir, file)
            local_file_path = os.path.join(local_path, file)
            self.logger.info("Downloading from %s to %s", remote_file_path, local_file_path)
            sftp_conn.get(remote_file_path, local_file_path)
    except Exception as e:
        error_message = f"An error occurred while downloading files from the " \
                        f"SFTP server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

get_dir_info_from_sftp(sftp_conn, dir_path)

This method retrieves file details like name, size, last modified date, permissions, and owner from SFTP.

Parameters:

Name Type Description Default
sftp_conn SFTP Connection Object

The SFTP connection object.

required
dir_path str

Directory from where the file details need to be retrieved.

required

Returns:

Name Type Description
tuple int

Number of files present in the directory and their details in a nested

dict

dictionary format.

Examples:

file_count, file_details = FileTransferUtils().SFTP(). get_dir_info_from_sftp(sftp_conn, '/Inbox/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def get_dir_info_from_sftp(self, sftp_conn: paramiko.SFTPClient,
                           dir_path: str) -> tuple[int, dict]:
    """
    This method retrieves file details like name, size, last modified date, permissions,
     and owner from SFTP.

    Args:
        sftp_conn (SFTP Connection Object): The SFTP connection object.
        dir_path (str): Directory from where the file details need to be retrieved.

    Returns:
        tuple: Number of files present in the directory and their details in a nested
        dictionary format.

    Examples:
        >> file_count, file_details = FileTransferUtils().SFTP().
        get_dir_info_from_sftp(sftp_conn, '/Inbox/')
    """
    try:
        file_details = {}
        file_list = sftp_conn.listdir_attr(dir_path)

        for index, file_attr in enumerate(file_list, start=1):
            file_details[f"file{index}"] = {
                "file name": file_attr.filename,
                "file size": file_attr.st_size,
                "file last modified date": str(datetime.fromtimestamp(file_attr.st_mtime)),
                "file permissions": oct(file_attr.st_mode)[-3:],
                "file owner": f"{file_attr.st_uid} {file_attr.st_gid}"
            }
        return len(file_details), file_details
    except Exception as e:
        error_message = f"An error occurred while retrieving directory info from " \
                        f"the SFTP server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

open_sftp_connection(sftp_host, sftp_port, sftp_username, sftp_password)

This method creates an SFTP connection.

Parameters:

Name Type Description Default
sftp_host str

Host name of the SFTP server.

required
sftp_port int

Port number for the SFTP server.

required
sftp_username str

Username for the SFTP server.

required
sftp_password str

Password for the SFTP server.

required

Returns:

Type Description
SFTPClient

SFTP Connection Object: The created SFTP connection object.

Examples:

sftp_conn = FileTransferUtils().SFTP(). open_sftp_connection('sftp.example.com', 22, 'username', 'password')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def open_sftp_connection(
        self, sftp_host: str, sftp_port: int, sftp_username: str,
        sftp_password: str
) -> paramiko.SFTPClient:
    """
    This method creates an SFTP connection.

    Args:
        sftp_host (str): Host name of the SFTP server.
        sftp_port (int): Port number for the SFTP server.
        sftp_username (str): Username for the SFTP server.
        sftp_password (str): Password for the SFTP server.

    Returns:
        SFTP Connection Object: The created SFTP connection object.

    Examples:
        >> sftp_conn = FileTransferUtils().SFTP().
        open_sftp_connection('sftp.example.com', 22, 'username', 'password')
    """
    try:

        sftp_connection, self.transport = FileTransferUtils().security.open_sftp_connection(
            sftp_host, sftp_port, sftp_username, sftp_password
        )
        return sftp_connection
    except Exception as e:
        error_message = f"An error occurred while connecting to the SFTP server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e

uploading_files_to_sftp(sftp_conn, upload_files, sftp_dir, local_path)

This method uploads files to SFTP.

Parameters:

Name Type Description Default
sftp_conn SFTP Connection Object

The SFTP connection object.

required
upload_files list

List of files that need to be uploaded.

required
sftp_dir str

Directory to where the files need to be uploaded.

required
local_path str

Local path from where the files need to be uploaded.

required

Examples:

FileTransferUtils().SFTP().uploading_files_to_sftp(sftp_conn, ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')

Source code in libs\cafex_core\src\cafex_core\utils\file_transfer_utils.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def uploading_files_to_sftp(
        self, sftp_conn: paramiko.SFTPClient, upload_files: list, sftp_dir: str,
        local_path: str
) -> None:
    """
    This method uploads files to SFTP.

    Args:
        sftp_conn (SFTP Connection Object): The SFTP connection object.
        upload_files (list): List of files that need to be uploaded.
        sftp_dir (str): Directory to where the files need to be uploaded.
        local_path (str): Local path from where the files need to be uploaded.

    Examples:
        >> FileTransferUtils().SFTP().uploading_files_to_sftp(sftp_conn,
        ['file1.pdf'], '/Inbox/', 'C:/Users/Project/')
    """
    try:
        os.makedirs(local_path, exist_ok=True)
        for file in upload_files:
            remote_file_path = os.path.join(sftp_dir, file)
            local_file_path = os.path.join(local_path, file)
            self.logger.info("Uploading from %s to %s", local_file_path, remote_file_path)
            sftp_conn.put(local_file_path, remote_file_path)
    except Exception as e:
        error_message = f"An error occurred while uploading files to the " \
                        f"SFTP server: {str(e)}"
        self.__obj_exception.raise_generic_exception(error_message)
        raise e