forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdropbox_client.py
More file actions
286 lines (252 loc) · 9.42 KB
/
Copy pathdropbox_client.py
File metadata and controls
286 lines (252 loc) · 9.42 KB
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
"""
Dropbox API client wrapper.
"""
import json
import re
from typing import Optional, Tuple
import requests
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
class DropboxClient:
"""Client for Dropbox API operations."""
API_BASE = "https://api.dropboxapi.com/2"
CONTENT_BASE = "https://content.dropboxapi.com/2"
def __init__(self, access_token: str):
self.access_token = access_token
def _headers(self, content_type: str = "application/json") -> dict:
"""Get standard headers for API requests."""
return {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": content_type,
}
@staticmethod
def sanitize_path(name: str) -> str:
"""
Sanitize a string to be safe for Dropbox paths.
Removes/replaces characters that are invalid in Dropbox paths.
"""
# Characters not allowed in Dropbox: < > : " / \ | ? *
invalid_chars = r'[<>:"/\\|?*]'
sanitized = re.sub(invalid_chars, "", name)
# Replace multiple spaces with single space
sanitized = re.sub(r"\s+", " ", sanitized)
# Trim to reasonable length
sanitized = sanitized[:100].strip()
# Ensure it's not empty
if not sanitized:
sanitized = "Untitled"
return sanitized
def get_account(self) -> Tuple[Optional[dict], Optional[str]]:
"""
Get current user's account info.
Returns (account_info, error_message).
"""
try:
response = requests.post(
f"{self.API_BASE}/users/get_current_account",
headers=self._headers(),
)
if response.status_code == 200:
return response.json(), None
else:
return None, f"Failed to get account: {response.text}"
except Exception as e:
return None, f"Error getting account: {str(e)}"
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError)),
)
def create_folder(self, path: str) -> Tuple[Optional[dict], Optional[str]]:
"""
Create a folder at the given path.
Returns (folder_metadata, error_message).
If folder already exists, returns success.
"""
try:
response = requests.post(
f"{self.API_BASE}/files/create_folder_v2",
headers=self._headers(),
json={"path": path, "autorename": False},
)
if response.status_code == 200:
return response.json(), None
elif response.status_code == 409:
# Folder already exists - this is fine
error_data = response.json()
if "path" in str(error_data) and "conflict" in str(error_data):
return {"path": path, "already_exists": True}, None
return None, f"Conflict: {response.text}"
else:
return None, f"Failed to create folder: {response.text}"
except Exception as e:
return None, f"Error creating folder: {str(e)}"
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError)),
)
def upload_file(
self,
path: str,
content: bytes,
mode: str = "overwrite",
) -> Tuple[Optional[dict], Optional[str]]:
"""
Upload a file to Dropbox.
For files < 150MB.
Returns (file_metadata, error_message).
"""
try:
# Dropbox-API-Arg header requires JSON
api_arg = json.dumps({
"path": path,
"mode": mode,
"autorename": True,
"mute": False,
})
headers = {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/octet-stream",
"Dropbox-API-Arg": api_arg,
}
response = requests.post(
f"{self.CONTENT_BASE}/files/upload",
headers=headers,
data=content,
)
if response.status_code == 200:
return response.json(), None
else:
return None, f"Failed to upload file: {response.text}"
except Exception as e:
return None, f"Error uploading file: {str(e)}"
def folder_exists(self, path: str) -> bool:
"""Check if a folder exists at the given path."""
try:
response = requests.post(
f"{self.API_BASE}/files/get_metadata",
headers=self._headers(),
json={"path": path},
)
if response.status_code == 200:
metadata = response.json()
return metadata.get(".tag") == "folder"
return False
except Exception:
return False
def ensure_folder_exists(self, path: str) -> Tuple[bool, Optional[str]]:
"""
Ensure a folder exists, creating it if necessary.
Returns (success, error_message).
"""
if self.folder_exists(path):
return True, None
result, error = self.create_folder(path)
if error and "already_exists" not in str(result):
return False, error
return True, None
def search_files(
self,
query: str,
path: str = "",
max_results: int = 10,
) -> Tuple[Optional[list], Optional[str]]:
"""
Search for files in Dropbox.
Returns (results_list, error_message).
"""
try:
payload = {
"query": query,
"options": {
"max_results": max_results,
"file_status": "active",
},
}
if path:
payload["options"]["path"] = path
response = requests.post(
f"{self.API_BASE}/files/search_v2",
headers=self._headers(),
json=payload,
)
if response.status_code == 200:
data = response.json()
matches = data.get("matches", [])
results = []
for match in matches:
metadata = match.get("metadata", {}).get("metadata", {})
results.append({
"name": metadata.get("name", "Unknown"),
"path": metadata.get("path_display", ""),
"type": metadata.get(".tag", "file"),
"size": metadata.get("size", 0),
"modified": metadata.get("server_modified", ""),
})
return results, None
else:
return None, f"Search failed: {response.text}"
except Exception as e:
return None, f"Error searching: {str(e)}"
def list_folder(
self,
path: str = "",
limit: int = 20,
) -> Tuple[Optional[list], Optional[str]]:
"""
List files in a folder.
Returns (files_list, error_message).
"""
try:
response = requests.post(
f"{self.API_BASE}/files/list_folder",
headers=self._headers(),
json={
"path": path if path else "",
"limit": limit,
"recursive": False,
},
)
if response.status_code == 200:
data = response.json()
entries = data.get("entries", [])
results = []
for entry in entries:
results.append({
"name": entry.get("name", "Unknown"),
"path": entry.get("path_display", ""),
"type": entry.get(".tag", "file"),
"size": entry.get("size", 0),
"modified": entry.get("server_modified", ""),
})
return results, None
else:
return None, f"List failed: {response.text}"
except Exception as e:
return None, f"Error listing: {str(e)}"
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError)),
)
def download_file(self, path: str) -> Tuple[Optional[bytes], Optional[str]]:
"""
Download a file from Dropbox.
Returns (file_bytes, error_message).
"""
try:
api_arg = json.dumps({"path": path})
headers = {
"Authorization": f"Bearer {self.access_token}",
"Dropbox-API-Arg": api_arg,
}
response = requests.post(
f"{self.CONTENT_BASE}/files/download",
headers=headers,
)
if response.status_code == 200:
return response.content, None
else:
return None, f"Failed to download file: {response.text}"
except Exception as e:
return None, f"Error downloading file: {str(e)}"