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requests
|
3 |
+
from googleapiclient.discovery import build
|
4 |
+
from google.oauth2 import service_account
|
5 |
+
from googleapiclient.http import MediaFileUpload
|
6 |
+
import io
|
7 |
+
|
8 |
+
################################
|
9 |
+
######### Variables ############
|
10 |
+
################################
|
11 |
+
# -- Get environment variables
|
12 |
+
CLIENT_ID = os.getenv('CLIENT_ID')
|
13 |
+
CLIENT_EMAIL = os.getenv('CLIENT_EMAIL')
|
14 |
+
PRIVATE_KEY_ID = os.getenv('PRIVATE_KEY_ID')
|
15 |
+
PRIVATE_KEY = os.getenv('PRIVATE_KEY').replace('\\n', '\n')
|
16 |
+
PROJECT_ID = os.getenv("PROJECT_ID")
|
17 |
+
CLIENT_X509_CERT_URL = os.getenv("CLIENT_X509_CERT_URL")
|
18 |
+
|
19 |
+
# -- Define your OAuth2 credentials directly
|
20 |
+
JSON_DATA = {
|
21 |
+
"type": "service_account",
|
22 |
+
"project_id": PROJECT_ID,
|
23 |
+
"private_key_id": PRIVATE_KEY_ID,
|
24 |
+
"private_key": PRIVATE_KEY,
|
25 |
+
"client_email": CLIENT_EMAIL,
|
26 |
+
"client_id": CLIENT_ID,
|
27 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
28 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
29 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
30 |
+
"client_x509_cert_url": CLIENT_X509_CERT_URL,
|
31 |
+
"universe_domain": "googleapis.com"
|
32 |
+
}
|
33 |
+
|
34 |
+
################################
|
35 |
+
####### GenericFunctions #######
|
36 |
+
################################
|
37 |
+
|
38 |
+
# -- Authentication
|
39 |
+
def get_drive_service():
|
40 |
+
"""
|
41 |
+
Authenticate and return the Google Drive API service.
|
42 |
+
"""
|
43 |
+
|
44 |
+
# Build and return the Drive service
|
45 |
+
credentials = service_account.Credentials.from_service_account_info(
|
46 |
+
JSON_DATA,
|
47 |
+
scopes=['https://www.googleapis.com/auth/drive']
|
48 |
+
)
|
49 |
+
service = build('drive', 'v3', credentials=credentials)
|
50 |
+
return service
|
51 |
+
|
52 |
+
# -- List all files
|
53 |
+
def list_all_files():
|
54 |
+
"""
|
55 |
+
List all file IDs and names in Google Drive.
|
56 |
+
"""
|
57 |
+
|
58 |
+
# Build the Drive service
|
59 |
+
drive_service = get_drive_service()
|
60 |
+
|
61 |
+
try:
|
62 |
+
results = drive_service.files().list(fields="nextPageToken, files(id, name)").execute()
|
63 |
+
files = results.get('files', [])
|
64 |
+
|
65 |
+
if not files:
|
66 |
+
print("No files found in Google Drive.")
|
67 |
+
else:
|
68 |
+
for file in files:
|
69 |
+
print(f"File ID: {file['id']}, Name: {file['name']}")
|
70 |
+
except Exception as e:
|
71 |
+
print(f"Error listing files: {e}")
|
72 |
+
raise e
|
73 |
+
|
74 |
+
# -- Get File ID from File Name
|
75 |
+
def get_files_id_by_name(file_names):
|
76 |
+
"""
|
77 |
+
List file IDs for specific file names in Google Drive.
|
78 |
+
"""
|
79 |
+
|
80 |
+
# Build the Drive service
|
81 |
+
drive_service = get_drive_service()
|
82 |
+
|
83 |
+
# Set the query parameters
|
84 |
+
fields = 'files(id, name)'
|
85 |
+
pageSize = 1000 # Set an appropriate page size to retrieve all files
|
86 |
+
|
87 |
+
# List the files matching the query
|
88 |
+
results = drive_service.files().list(
|
89 |
+
fields=fields,
|
90 |
+
pageSize=pageSize
|
91 |
+
).execute()
|
92 |
+
files = results.get('files', [])
|
93 |
+
|
94 |
+
return files[0]
|
95 |
+
|
96 |
+
|
97 |
+
# -- Create a new file
|
98 |
+
def create_file(file_path):
|
99 |
+
"""
|
100 |
+
Create a new file on Google Drive.
|
101 |
+
"""
|
102 |
+
|
103 |
+
# Build the Drive service
|
104 |
+
print(file_path)
|
105 |
+
drive_service = get_drive_service()
|
106 |
+
|
107 |
+
try:
|
108 |
+
file_name = os.path.basename(file_path)
|
109 |
+
media = MediaFileUpload(file_path, mimetype='application/octet-stream')
|
110 |
+
file_metadata = {'name': file_name}
|
111 |
+
file = drive_service.files().create(
|
112 |
+
body=file_metadata,
|
113 |
+
media_body=media,
|
114 |
+
fields='id'
|
115 |
+
).execute()
|
116 |
+
print(f"Uploaded '{file_name}' with ID: {file['id']}")
|
117 |
+
|
118 |
+
return file
|
119 |
+
except Exception as e:
|
120 |
+
print(f"Upload error: {e}")
|
121 |
+
raise e
|
122 |
+
|
123 |
+
# -- Update existing file
|
124 |
+
def update_file(file_path):
|
125 |
+
"""
|
126 |
+
Update an existing file on Google Drive.
|
127 |
+
"""
|
128 |
+
|
129 |
+
# Build the Drive service
|
130 |
+
drive_service = get_drive_service()
|
131 |
+
|
132 |
+
try:
|
133 |
+
# get file id
|
134 |
+
file_name = os.path.basename(file_path)
|
135 |
+
file_id = get_files_id_by_name(file_name)
|
136 |
+
file_metadata = {
|
137 |
+
'name': file_name
|
138 |
+
}
|
139 |
+
|
140 |
+
# Update the file
|
141 |
+
media_body = MediaFileUpload(file_path, mimetype='application/octet-stream')
|
142 |
+
file = drive_service.files().update(
|
143 |
+
fileId=file_id['id'],
|
144 |
+
body=file_metadata,
|
145 |
+
media_body=media_body
|
146 |
+
).execute()
|
147 |
+
print(f"Uploaded '{file_name}' with ID: {file['id']}")
|
148 |
+
return file
|
149 |
+
|
150 |
+
except Exception as e:
|
151 |
+
print(f"Upload error: {e}")
|
152 |
+
raise e
|
153 |
+
|
154 |
+
# -- Donwload file to local
|
155 |
+
def download_file(file_name, save_path):
|
156 |
+
"""
|
157 |
+
Download Google Drive to local
|
158 |
+
"""
|
159 |
+
|
160 |
+
# Build the Drive service
|
161 |
+
drive_service = get_drive_service()
|
162 |
+
|
163 |
+
try:
|
164 |
+
file_id = get_files_id_by_name(file_name)
|
165 |
+
request = drive_service.files().get_media(fileId=file_id['id'])
|
166 |
+
fh = io.FileIO(save_path+file_name, 'wb')
|
167 |
+
|
168 |
+
# Download the file in chunks and write to the local file
|
169 |
+
downloader = request.execute().decode("utf-8")
|
170 |
+
|
171 |
+
if 'size' in downloader:
|
172 |
+
file_size = int(downloader['size'])
|
173 |
+
chunk_size = 1024 * 1024 # 1MB chunks (adjust as needed)
|
174 |
+
|
175 |
+
while downloader:
|
176 |
+
if 'data' in downloader:
|
177 |
+
fh.write(downloader['data'].encode('utf-8'))
|
178 |
+
status, downloader = service.files().get_media(fileId=file_id, downloadStatus=status).execute()
|
179 |
+
print(f"Downloaded {fh.tell()}/{file_size} bytes.")
|
180 |
+
else:
|
181 |
+
fh.write(downloader.encode('utf-8'))
|
182 |
+
|
183 |
+
print(f"Downloaded file '{file_id}' to '{save_path}'")
|
184 |
+
except Exception as e:
|
185 |
+
print(f"Download error: {e}")
|
186 |
+
raise e
|
187 |
+
|
188 |
+
# -- Delete a file by its ID
|
189 |
+
def delete_file(file_id):
|
190 |
+
"""
|
191 |
+
Delete a file in Google Drive by its ID.
|
192 |
+
"""
|
193 |
+
|
194 |
+
# Build the Drive service
|
195 |
+
drive_service = get_drive_service()
|
196 |
+
|
197 |
+
# Deleting specific file
|
198 |
+
try:
|
199 |
+
drive_service.files().delete(fileId=file_id).execute()
|
200 |
+
print(f"Deleted file with ID: {file_id}")
|
201 |
+
except Exception as e:
|
202 |
+
print(f"Error deleting file with ID {file_id}: {e}")
|
203 |
+
raise e
|
204 |
+
|
205 |
+
# -- List and delete all files
|
206 |
+
def delete_all_files():
|
207 |
+
"""
|
208 |
+
List and delete all files in Google Drive.
|
209 |
+
"""
|
210 |
+
|
211 |
+
# Build the Drive service
|
212 |
+
drive_service = get_drive_service()
|
213 |
+
|
214 |
+
# Set the query parameters to list all files
|
215 |
+
fields = 'files(id, name)'
|
216 |
+
pageSize = 1000 # Set an appropriate page size to retrieve all files
|
217 |
+
|
218 |
+
try:
|
219 |
+
# List all files
|
220 |
+
results = drive_service.files().list(
|
221 |
+
fields=fields,
|
222 |
+
pageSize=pageSize
|
223 |
+
).execute()
|
224 |
+
files = results.get('files', [])
|
225 |
+
|
226 |
+
# Delete each file in the list
|
227 |
+
for file in files:
|
228 |
+
delete_file(file['id'])
|
229 |
+
except Exception as e:
|
230 |
+
print(f"Error deleting files: {e}")
|
231 |
+
raise e
|