forked from thedomino1313/DiscordDrive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
drive.py
343 lines (283 loc) · 13.1 KB
/
drive.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
from inspect import getfullargspec, isawaitable
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from discord import Attachment, File, ApplicationContext, Client, DMChannel
from zipfile import ZipFile, BadZipFile
from mimetypes import guess_type
from io import BytesIO, open
import sys
from utils import *
class DriveAPI:
ROOT = ""
ROOT_ID = ""
folders = dict()
service = None
FOLDER_TYPE = "application/vnd.google-apps.folder"
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.activity", "https://www.googleapis.com/auth/drive.metadata"]
def _input_validator(func):
def _validate(self, *args, **kwargs):
argspecs = getfullargspec(func)
annotations = argspecs.annotations
argnames = argspecs.args
for val, arg in zip(args, argnames[1:len(args) + 1]):
assert val is not None, f"Argument '{arg}' is None, please do not use None as an argument"
assert isinstance(val, annotations[arg]), f"Argument '{arg}' is not of the type '{str(annotations[arg])[8:-2]}'."
for arg in kwargs:
assert kwargs[arg] is not None, f"Argument '{arg}' is None, please do not use None as an argument."
assert isinstance(kwargs[arg], annotations[arg]), f"Argument '{arg}' is not of the type '{str(annotations[arg])[8:-2]}'."
return func(self, *args, **kwargs)
return _validate
def _temp_dir_async(path):
def _temp_decorator(func):
async def _temp_manager(self, *args, **kwargs):
if not os.path.exists(path):
os.mkdir(path)
else:
empty_dir(path)
ret = await func(self, *args, **kwargs)
empty_dir(path)
os.rmdir(path)
return ret
return _temp_manager
return _temp_decorator
def _temp_dir(path):
def _temp_decorator(func):
def _temp_manager(self, *args, **kwargs):
if not os.path.exists(path):
os.mkdir(path)
else:
empty_dir(path)
ret = func(self, *args, **kwargs)
empty_dir(path)
os.rmdir(path)
return ret
return _temp_manager
return _temp_decorator
# auth_url, _ = flow.authorization_url(prompt='consent')
# print('Please go to this URL: {}'.format(auth_url))
# # The user will get an authorization code. This code is used to get the
# # access token.
# code = input('Enter the authorization code: ')
# creds = flow.fetch_token(code=code)
# with open("token.json", "w") as token:
# token.write(creds.to_json())
@_input_validator
def __init__(self, root:str):
if not root:
raise Exception("A root directory must be provided.")
self.ROOT = root
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", self.SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
try:
creds.refresh(Request())
with open("token.json", "w") as token:
token.write(creds.to_json())
self.create_service(creds)
except:
pass
else:
self.create_service(creds)
@_input_validator
async def authenticate(self, ctx: ApplicationContext, bot: Client):
if self.service:
await ctx.respond("You are already authenticated!")
return
flow = InstalledAppFlow.from_client_secrets_file(
"credentials.json", self.SCOPES,
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
auth_url, _ = flow.authorization_url(prompt='consent', )
response = await ctx.respond("Check your DMs!")
await ctx.author.send(f'Please go to [this URL]({auth_url}) and respond with the authorization code.')
def check(m):
return isinstance(m.channel, DMChannel) and m.author == ctx.author
msg = await bot.wait_for("message", check=check)
flow.fetch_token(code=msg.content)
creds = flow.credentials
with open("token.json", "w") as token:
token.write(creds.to_json())
self.create_service(creds)
await ctx.author.send("Authentication Complete!")
await response.edit("Authentication Complete!")
@_input_validator
def create_service(self, creds: Credentials):
try:
self.service = build("drive", "v3", credentials=creds)
folder = self.search(file_name=self.ROOT, files=False)
if not folder:
raise Exception("No folders found, check the root name.")
folder = folder[0]
self.ROOT = folder["name"]
self.ROOT_ID = folder["id"]
self.folders[folder['name']] = folder['id']
print(f"Found folder '{folder['name']}' with id '{folder['id']}'")
except HttpError as error:
# TODO(developer) - Handle errors from drive API.
print(f"An error occurred: {error}")
# @_input_validator
# def folder_id_lookup(self, folder:str) -> str:
# if not folder:
# raise Exception("Folder name cannot be an empty string.")
# try:
# return self.folders[folder]
# except:
# found_folder = self.search(name=folder, files=False)[0]
# if not found_folder:
# raise HttpError("No folders were found")
# self.folders[found_folder["name"]] = found_folder["id"]
# return found_folder["id"]
@_input_validator
def update_folders(self, flist:list) -> None:
for file in flist:
if file["mimeType"] == self.FOLDER_TYPE:
self.folders[file["name"]] = file["id"]
@_input_validator
def search(self, file_name:str='', parent:str='', page_size:int=1, files:bool=True, folders:bool=True, page_token:str='', recursive:bool=False) -> list:
"""Modular search function that can find files and folders, with the option of a specified parent directory.
Args:
file_name (str, optional): Name of a specific file/folder to find. Defaults to ''.
parent (str, optional): Name of a parent folder to search inside of. Defaults to ''.
page_size (int, optional): Number of results to return. Defaults to 1.
files (bool, optional): Enable searching for files. Defaults to True.
folders (bool, optional): Enable searching for folders. Defaults to True.
pageToken (str, optional): Token for the next page of results. Defaults to ''.
recursive (bool, optional): Search all pages for all results. Defaults to False.
Raises:
Exception: Any input parameters are None
Exception: Both the name and parent fields are left blank
Returns:
list(dict): A list of the files found. Format: [{'mimeType': 'application/vnd.google-apps.folder', 'id': '1FkOWqVDhbj8y5N7gq7-XQqQjCceMVLN9', 'name': 'Example'},...]
"""
# Generate the search parameter for a file name
nameScript = f" and name = '{file_name}'" if file_name else ""
# Generate the search parameter for a parent folder
try:
parentScript = f" and '{parent}' in parents" if parent else ""
except HttpError as error:
print(f"The parent folder does not exist: {error}")
return None, None
if nameScript == parentScript:
raise Exception("Both parameters cannot be empty.")
if files and folders:
mimeScript = ""
elif files:
mimeScript = f"and mimeType!='{self.FOLDER_TYPE}'"
else:
mimeScript = f"and mimeType='{self.FOLDER_TYPE}'"
try:
results = (
self.service.files()
.list(pageSize=page_size,
pageToken=page_token,
q=f"trashed = false{mimeScript}{nameScript}{parentScript}",
orderBy="folder, name",
fields="nextPageToken, files(id, name, mimeType)")
.execute()
)
foundfiles = results.get("files", [])
self.update_folders(foundfiles)
if (page_token := results.get("nextPageToken", "")) and recursive:
return foundfiles + self.search(file_name=file_name, page_size=page_size, parent=parent, files=files, folders=folders, page_token=page_token, recursive=recursive)
return foundfiles
except HttpError as error:
print(f"An error occurred: {error}")
return None
@_temp_dir_async("temp")
@_input_validator
async def upload_from_discord(self, file:Attachment, parent:str=""):
file_name = f"temp/{file.filename}"
await file.save(file_name)
try:
with ZipFile(file_name, 'r') as zf:
zf.extractall("temp")
os.remove(file_name)
flist = [self.upload(file_name, mimetype, local_path="temp", parent=parent) for file_name in os.listdir("temp") if (mimetype := guess_type(os.path.join("temp", file_name))[0]) is not None]
if len(flist) != len(os.listdir("temp")):
s = "Please ensure that there are no folders inside of the zip file, as they and their contents will not be uploaded.\n"
else: s = ""
return f"{s}File{'s' if len(flist) != 1 else ''} `{', '.join(flist)}` uploaded!"
except BadZipFile:
return f"File `{self.upload(file.filename, file.content_type, local_path='temp', parent=parent)}` uploaded!"
@_input_validator
def upload(self, file_name:str, content_type:str, local_path:str=".", parent:str=""):
if not parent:
parent = self.ROOT
file_metadata = {
"name": file_name,
"mimeType": content_type,
"parents": [parent]}
media = MediaFileUpload(local_path + "/" + file_name, mimetype=content_type)
try:
file_name = (
self.service.files()
.create(body=file_metadata, media_body=media, fields="name")
.execute()
)
return file_name["name"]
except HttpError as error:
print(f"An error occurred: {error}")
return None
@_input_validator
def make_folder(self, file_name:str, parent:str=""):
if not parent:
parent = self.ROOT
file_metadata = {
"name": file_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [parent]
}
try:
file = (
self.service.files()
.create(body=file_metadata, fields="id")
.execute()
)
self.folders[file_name] = file["id"]
return True
except HttpError:
return False
@_temp_dir("temp")
@_input_validator
def export(self, file_name:str, parent:str=""):
if not parent:
parent = self.ROOT
file = self.search(file_name=file_name, parent=parent, folders=False)
if not file:
return "File not found."
real_file_id = file[0]["id"]
try:
file_id = real_file_id
# pylint: disable=maybe-no-member
request = (
self.service.files()
.get_media(fileId=file_id)
)
file = BytesIO()
downloader = MediaIoBaseDownload(file, request)
done = False
while done is False:
status, done = downloader.next_chunk()
# print(f"Download {int(status.progress() * 100)}.")
filepath = os.path.join("temp", file_name)
with open(filepath, "wb") as f:
file.seek(0)
f.write(file.read())
fileObj = file = File(filepath)
return fileObj
except HttpError:
return "An error occured retrieving this file."
if __name__ == "__main__":
API = DriveAPI("Textbooks")
# print("\n".join([f"{result['name']} is of type {result['mimeType']} with ID {result['id']}" for result in API.search(pageSize=100, parent=API.root["name"])]))
API.export("CogSciBook.pdf")