brynq-sdk-google-drive 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ from .google_drive import GoogleDrive
@@ -0,0 +1,164 @@
1
+ import os
2
+ from typing import List, Union, Literal, Optional
3
+ import requests
4
+ import json
5
+ from io import BytesIO
6
+ import typing
7
+ from googleapiclient.discovery import build
8
+ from googleapiclient.http import MediaFileUpload
9
+ from brynq_sdk_brynq import BrynQ
10
+
11
+ class GoogleDrive(BrynQ):
12
+ def __init__(self, system_type: Optional[Literal['source', 'target']] = None, debug: bool = False):
13
+ """
14
+ :param label: label of the Google Drive system in BrynQ
15
+ :param debug: set to True to enable debug logging
16
+ """
17
+ super().__init__()
18
+ api_version = 'v3'
19
+ self.system_type = system_type
20
+ self.base_url = f'https://www.googleapis.com/drive/{api_version}/'
21
+ credentials = self.interfaces.credentials.get(system="google-drive", system_type=system_type)
22
+ self.credentials = credentials.get('data')
23
+ self.debug = debug
24
+ if self.debug:
25
+ print(f"credentials: {credentials}")
26
+ self.access_token = credentials['access_token']
27
+ self.timeout = 3600
28
+
29
+ def _refresh_credentials(self):
30
+ credentials = self.interfaces.credentials.get(system="sharepoint", system_type=self.system_type)
31
+ credentials = credentials.get('data')
32
+ self.access_token = credentials['access_token']
33
+
34
+ def _get_google_drive_headers(self):
35
+ self._refresh_credentials()
36
+ headers = {'Authorization': f'Bearer {self.access_token}'}
37
+ if self.debug:
38
+ print(headers)
39
+ return headers
40
+
41
+ def list_files(self, drive_id: str = None):
42
+ """
43
+ Get all files from Google Drive, including shared drives or a specific drive is specified
44
+ :param drive_id: ID of a specific drive (optional)
45
+ """
46
+ url = f'{self.base_url}files'
47
+ headers = self._get_google_drive_headers()
48
+ params = {
49
+ 'supportsAllDrives': True,
50
+ 'includeItemsFromAllDrives': True,
51
+ }
52
+ if drive_id:
53
+ params['driveId'] = drive_id
54
+ params['corpora'] = 'drive'
55
+ response = requests.get(url=url, headers=headers, params=params, timeout=self.timeout)
56
+ response.raise_for_status()
57
+ return response
58
+
59
+ def upload_file(self, local_file_path: str, remote_file_path: str):
60
+ """
61
+ This method performs the actual file upload to the formerly derived site + drive.
62
+ local_file_path: local path of the file you want to upload
63
+ remote_file_path: remote path of the folder and filename where you want to place the file
64
+ """
65
+ service = build('drive', 'v3', credentials=self.credentials)
66
+
67
+ file_metadata = {'name': os.path.basename(remote_file_path)}
68
+ media = MediaFileUpload(local_file_path, resumable=True)
69
+
70
+ response = service.files().create(
71
+ body=file_metadata,
72
+ media_body=media,
73
+ fields='id'
74
+ ).execute()
75
+
76
+ if self.debug:
77
+ print(f'File ID: {response.get("id")}')
78
+
79
+ return response
80
+
81
+ def download_file(self, file_id: str, mime_type: str, local_file_path: str):
82
+ """
83
+ This method downloads a file from Google Drive to the local machine.
84
+ file_id: id of the file on Google Drive. Get it with the list_files function
85
+ mime_type: mime type of the file. Get it with the list_files function
86
+ local_file_path: local path where the file will be downloaded to
87
+ """
88
+ url = f'{self.base_url}files/{file_id}/export?mimeType={mime_type}'
89
+ headers = self._get_google_drive_headers()
90
+ response = requests.get(url=url, headers=headers, timeout=self.timeout)
91
+ response.raise_for_status()
92
+ with open(local_file_path, 'wb') as f:
93
+ f.write(response.content)
94
+ return response
95
+
96
+ def download_files(self, local_folder_path: str, remote_folder_path: str):
97
+ """
98
+ This method downloads all files from a Directory in Google Drive to the local machine.
99
+ local_folder_path: local folder where the files will be downloaded to
100
+ remote_folder_path: remote path of the folder you want to get on Google Drive
101
+ """
102
+ service = build('drive', 'v3', credentials=self.credentials)
103
+
104
+ # List files in the specified remote folder
105
+ query = f"'{remote_folder_path}' in parents"
106
+ results = service.files().list(q=query, fields="files(id, name)").execute()
107
+ items = results.get('files', [])
108
+
109
+ if not items:
110
+ return 'No files found.'
111
+ else:
112
+ for item in items:
113
+ file_id = item['id']
114
+ file_name = item['name']
115
+ request = service.files().get_media(fileId=file_id)
116
+ fh = BytesIO()
117
+ downloader = MediaIoBaseDownload(fh, request)
118
+ done = False
119
+ while done is False:
120
+ status, done = downloader.next_chunk()
121
+ if self.debug:
122
+ print(f"Download {file_name} {int(status.progress() * 100)}%.")
123
+
124
+ # Save the file to the local folder
125
+ local_file_path = os.path.join(local_folder_path, file_name)
126
+ with open(local_file_path, 'wb') as f:
127
+ f.write(fh.getvalue())
128
+
129
+ return "Download complete"
130
+
131
+ def remove_file(self, remote_file_path: str):
132
+ """
133
+ Remove a file from Google Drive
134
+ remote_file_path: complete path including filename
135
+ :return: response from Google Drive
136
+ """
137
+ service = build('drive', 'v3', credentials=self.credentials)
138
+
139
+ # Find the file ID
140
+ query = f"name = '{remote_file_path}'"
141
+ results = service.files().list(q=query, fields="files(id)").execute()
142
+ items = results.get('files', [])
143
+
144
+ if not items:
145
+ print('No files found.')
146
+ return "No files found."
147
+ else:
148
+ file_id = items[0]['id']
149
+ response = service.files().delete(fileId=file_id).execute()
150
+ if self.debug:
151
+ print(f'File {remote_file_path} deleted.')
152
+ return response
153
+
154
+ def remove_folder(self, folder_id: str):
155
+ """
156
+ Remove a folder from Google Drive
157
+ folder: folder id that you want to delete
158
+ """
159
+ service = build('drive', 'v3', credentials=self.credentials)
160
+
161
+ response = service.files().delete(fileId=folder_id).execute()
162
+ if self.debug:
163
+ print(f'Folder {folder_id} deleted.')
164
+ return response
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.4
2
+ Name: brynq_sdk_google_drive
3
+ Version: 2.0.0
4
+ Summary: Google Drive wrapper from BrynQ
5
+ Author: BrynQ
6
+ Author-email: support@brynq.com
7
+ License: BrynQ License
8
+ Requires-Dist: brynq-sdk-brynq<5,>=4
9
+ Requires-Dist: google-api-python-client<3,>=2
10
+ Requires-Dist: requests<=3,>=2
11
+ Dynamic: author
12
+ Dynamic: author-email
13
+ Dynamic: description
14
+ Dynamic: license
15
+ Dynamic: requires-dist
16
+ Dynamic: summary
17
+
18
+ Groogle Drive wrapper from BrynQ
@@ -0,0 +1,6 @@
1
+ brynq_sdk_google_drive/__init__.py,sha256=_ypLX0AgrbtxNRQmxrpnbibWC8M-aaScXZdO8fWaeNo,37
2
+ brynq_sdk_google_drive/google_drive.py,sha256=q-CMwvo7TynIdfvk_1mA2k6eF_eGLTl_HVtKJxvYHo8,6496
3
+ brynq_sdk_google_drive-2.0.0.dist-info/METADATA,sha256=p4PiE210FFQJj3PsmOE9LHY_qmhYf4gXzMzzi91HwKo,440
4
+ brynq_sdk_google_drive-2.0.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
5
+ brynq_sdk_google_drive-2.0.0.dist-info/top_level.txt,sha256=-MxuugDaqSPt_-3Yc03CWnXiZ7ryLNGYUnBdjoqiBrU,23
6
+ brynq_sdk_google_drive-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ brynq_sdk_google_drive