forked from caseymrm/drivesink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
drivesink.py
executable file
·292 lines (257 loc) · 11.2 KB
/
drivesink.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
#!/usr/bin/env python
import argparse
import hashlib
import json
import logging
import os
import requests
import requests_toolbelt
import uuid
class CloudNode(object):
def __init__(self, node):
self.node = node
self._children_fetched = False
def children(self):
if not self._children_fetched:
nodes = DriveSink.instance().request_metadata(
"%%snodes/%s/children" % self.node["id"])
self._children = {n["name"]: CloudNode(n) for n in nodes["data"]}
self._children_fetched = True
return self._children
def child(self, name, create=False):
node = self.children().get(name)
if not node and create:
node = self._make_child_folder(name)
return node
# based on http://stackoverflow.com/questions/35817/how-to-escape-os-system-calls-in-python
def shellquote(self, s):
return "'" + s.replace("'", "'\\''") + "'"
# based on https://github.com/cnbeining/Amazon-Cloud-Drive-Python-SDK/blob/master/acd.py
def upload_file_curl(self, local_path, parents='', labels = '', properties = []):
name = os.path.basename(local_path)
url = DriveSink.instance()._config()["contentUrl"] + 'nodes?&suppress=deduplication'
metadata = {"name": name, "kind": "FILE"}
if parents:
metadata['parents'] = parents
if labels:
metadata['labels'] = labels
if properties:
metadata['properties'] = properties
metadataform = self.shellquote("metadata=" + json.dumps(metadata))
contentform = self.shellquote("content=@" + local_path)
command = 'curl -k -X POST --form {metadata} --form {content} "{url}" --header "{Authorization}"' .format(metadata = metadataform, content = contentform, url = url, Authorization = "Authorization: Bearer %s" % DriveSink.instance()._config()["access_token"])
logging.debug(command)
tmp = os.popen(command).readlines()
#logging.debug(tmp[0])
return json.loads(tmp[0])
def upload_child_file(self, name, local_path, existing_node=None):
logging.info("Uploading %s to %s", local_path, self.node["name"])
node = self.upload_file_curl(local_path, parents=[self.node["id"]] )
"""
m = requests_toolbelt.MultipartEncoder([
("metadata", json.dumps({
"name": name,
"kind": "FILE",
"parents": [self.node["id"]]
})),
("content", (name, open(local_path, "rb")))])
if existing_node:
# TODO: this is under-documented and currently 500s on Amazon's side
node = CloudNode(DriveSink.instance().request_content(
"%%snodes/%s/content" % existing_node.node["id"],
method="put", data=m, headers={"Content-Type": "multipart/form-data"}))
old_info = DriveSink.instance().request_metadata(
"%%s/trash/%s" % existing_node.node["id"], method="put")
node = CloudNode(DriveSink.instance().request_content(
"%snodes?localId=a", method="post", data=m, headers={"Content-Type": "multipart/form-data"}))
"""
self._children[name] = node
def download_file(self, local_path):
logging.info("Downloading %s into %s", self.node["name"], local_path)
req = DriveSink.instance().request_content(
"%%snodes/%s/content" % self.node["id"], method="get", stream=True,
decode=False)
if req.status_code != 200:
logging.error("Unable to download file: %r", req.text)
exit(1)
with open(local_path, "wb") as f:
for chunk in req.iter_content():
f.write(chunk)
def differs(self, local_path):
return (not os.path.exists(local_path) or
self.node["contentProperties"]["size"] !=
os.path.getsize(local_path) or
self.node["contentProperties"]["md5"] !=
self._md5sum(local_path))
def _md5sum(self, filename, blocksize=65536):
md5 = hashlib.md5()
with open(filename, "r+b") as f:
for block in iter(lambda: f.read(blocksize), ""):
md5.update(block)
return md5.hexdigest()
def _make_child_folder(self, name):
logging.info(
"Creating remote folder %s in %s", name, self.node["name"])
node = CloudNode(
DriveSink.instance().request_metadata("%snodes", {
"kind": "FOLDER",
"name": name,
"parents": [self.node["id"]]}))
self._children[name] = node
return node
class DriveSink(object):
def __init__(self, args):
if not args:
logging.error("Never initialized")
exit(1)
self.args = args
self.config = None
@classmethod
def instance(cls, args=None):
if not hasattr(cls, "_instance"):
cls._instance = cls(args)
return cls._instance
def upload(self, source, destination):
remote_node = self.node_at_path(
self.get_root(), destination, create_missing=True)
for dirpath, dirnames, filenames in os.walk(source):
relative = dirpath[len(source):]
current_dir = self.node_at_path(
remote_node, relative, create_missing=True)
if not current_dir:
logging.error("Could not create missing node")
exit(1)
for dirname in dirnames:
current_dir.child(dirname, create=True)
for filename in filenames:
local_path = os.path.join(dirpath, filename)
node = current_dir.child(filename)
if (not node or node.differs(
local_path)) and self.filter_file(filename):
current_dir.upload_child_file(filename, local_path, node)
def download(self, source, destination):
to_download = [(self.node_at_path(self.get_root(), source),
self.join_path(destination, create_missing=True))]
while len(to_download):
node, path = to_download.pop(0)
for name, child in node.children().iteritems():
if child.node["kind"] == "FOLDER":
to_download.append((child, self.join_path(
child.node["name"], path, create_missing=True)))
elif child.node["kind"] == "FILE":
local_path = os.path.join(path, child.node["name"])
if child.differs(local_path):
child.download_file(local_path)
def filter_file(self, filename):
extension = filename.split(".")[-1]
allowed = self.args.extensions
if not allowed:
# Not all tested to be free
allowed = (
"apng,arw,bmp,cr2,crw,dng,emf,gif,jfif,jpe,jpeg,jpg,mef,nef," +
"orf,pcx,png,psd,raf,ras,srw,swf,tga,tif,tiff,wmf")
return extension in allowed.split(",")
def get_root(self):
nodes = self.request_metadata("%snodes?filters=isRoot:true")
if nodes["count"] != 1:
logging.error("Could not find root")
exit(1)
return CloudNode(nodes["data"][0])
def node_at_path(self, root, path, create_missing=False):
parts = filter(None, path.split("/"))
node = root
while len(parts):
node = node.child(parts.pop(0), create=create_missing)
if not node:
return None
return node
def join_path(self, destination, root="/", create_missing=True):
directory = os.path.join(root, destination)
if not os.path.exists(directory):
if create_missing:
os.makedirs(directory)
else:
return None
if not os.path.isdir(directory):
logging.error("%s is not a directory", directory)
exit(1)
return directory
def _config_file(self):
config_filename = self.args.config or os.environ.get(
"DRIVESINK", None)
if not config_filename:
config_filename = os.path.join(
os.path.expanduser("~"), ".drivesink")
return config_filename
def _config(self):
if not self.config:
config_filename = self._config_file()
try:
self.config = json.loads(open(config_filename, "r").read())
except:
print "%s/config to get your tokens" % self.args.drivesink
exit(1)
return self.config
def request_metadata(self, path, json_data=None, **kwargs):
args = {}
if json_data:
args["method"] = "post"
args["data"] = json.dumps(json_data)
else:
args["method"] = "get"
args.update(kwargs)
return self._request(
path % self._config()["metadataUrl"], **args)
def request_content(self, path, **kwargs):
return self._request(
path % self._config()["contentUrl"], **kwargs)
def _request(self, url, refresh=True, decode=True, **kwargs):
headers = {
"Authorization": "Bearer %s" % self._config()["access_token"],
}
headers.update(kwargs.pop("headers", {}))
req = requests.request(url=url, headers=headers, **kwargs)
if req.status_code == 401 and refresh:
# Have to proxy to get the client id and secret
req = requests.post("%s/refresh" % self.args.drivesink, data={
"refresh_token": self._config()["refresh_token"],
})
req.raise_for_status()
try:
new_config = req.json()
except:
logging.error("Could not refresh: %r", req.text)
raise
self.config.update(new_config)
with open(self._config_file(), "w") as f:
f.write(json.dumps(self.config, sort_keys=True, indent=4))
return self._request(url, refresh=False, decode=decode, **kwargs)
req.raise_for_status()
if decode:
return req.json()
return req
def main():
parser = argparse.ArgumentParser(
description="Amazon Cloud Drive synchronization tool")
parser.add_argument("command", choices=["upload", "download"],
help="Commands: 'upload' or 'download'")
parser.add_argument("source", help="The source directory")
parser.add_argument("destination", help="The destination directory")
parser.add_argument("-e", "--extensions",
help="File extensions to upload, images by default")
parser.add_argument("-c", "--config", help="The config file")
parser.add_argument("-d", "--drivesink", help="Drivesink URL",
default="https://drivesink.appspot.com")
args = parser.parse_args()
drivesink = DriveSink.instance(args)
if args.command == "upload":
drivesink.upload(args.source, args.destination)
elif args.command == "download":
drivesink.download(args.source, args.destination)
logging.basicConfig(
format = "%(levelname) -10s %(module)s:%(lineno)s %(funcName)s %(message)s",
level = logging.DEBUG
)
logging.getLogger("requests").setLevel(logging.WARNING)
if __name__ == "__main__":
main()