/
dropbox-paper-backup.py
executable file
·303 lines (240 loc) · 11.2 KB
/
dropbox-paper-backup.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
#!/usr/bin/env python3
# encoding: utf-8
""" Dropbox Backup
Usage:
{cmd} [--token=TOKEN] [--logfile=PATH] [--workers=NUM] [--verbose] [markdown|html] <target>
Options:
-t --token=TOKEN The access token for the dropbox account. Omit to get a new token.
-l --logfile=PATH Log to the specified file.
-v --verbose Be more verbose.
-w --workers=NUM Number of parallel workers [default: 5]
markdown|html Export either as "html" or as "markdown". Do both if omitted.
<target> The path to store the backup in.
"""
import io
import logging
import os
import re
import sys
import traceback
import unicodedata
import urllib.parse
import webbrowser
from contextlib import contextmanager
from concurrent.futures import ThreadPoolExecutor as Pool
import docopt
import dropbox
import requests
import requests.packages.urllib3
# API-Description: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-list
APP_KEY = "yb0prv4vj0ckhdt"
APP_SECRET = b'J,/ |+N5-Y\x12:-1\r'
def obf(s: bytes):
m = b'9NKLJCxPZikUXXgbTOVU'
return bytes(c ^ m[i % len(m)] for i, c in enumerate(s))
class Tracker(object):
""" Organize file structure and keep the archive clean.
Instances of this class organize where to place what files based on the given folder
structure and keep track of the seen files to simplify cleanup unused files afterwards.
"""
def __init__(self, path: str):
""" Create enw tracker instance.
:param path: Path to the archive.
"""
self.index = []
self.path = path
for dir_path, dir_names, file_names in os.walk(path):
for name in dir_names + file_names:
self.index.append(unicodedata.normalize('NFC', os.path.join(dir_path, name)))
def cleanup(self):
""" Remove all files in archive that where not requested since initialization. """
for path in sorted(self.index, reverse=True, key=len):
if os.path.isfile(path):
try:
os.unlink(str(path))
logging.debug('removed file %r', path)
except OSError:
pass
elif os.path.isdir:
try:
if not os.listdir(str(path)):
os.rmdir(str(path))
logging.debug('removed folder %r', path)
except OSError:
pass
def used(self, path: str):
""" Mark a file as seen by it's absolute path.
:param path: Absolute path to the file to mark as seen.
"""
normalized_path = unicodedata.normalize('NFC', path)
if normalized_path in self.index:
self.index.remove(normalized_path)
return True
else:
return False
@contextmanager
def file_handler(self, folders: list, file_name: str):
""" Get a file handler to store a new file.
:param folders: List of path elements to store the file at.
:param file_name: Name of the file to store
:rtype: Union[None, File]
:return: None if the file already exists or a file handler.
"""
if folders:
file_dir = os.path.join(*folders)
else:
file_dir = ''
if not self.used(file_dir):
try:
absolute_dir = os.path.join(self.path, file_dir)
os.makedirs(absolute_dir)
logging.debug('created folder %r', absolute_dir)
except FileExistsError:
pass
absolute_path = os.path.join(self.path, file_dir, file_name)
if not self.used(absolute_path):
with open(absolute_path, 'wb') as fd:
logging.debug('created file %r', absolute_path)
yield fd
else:
yield None
def paper_documents(dbx: dropbox.Dropbox, page_size=1000):
""" Get all dropbox paper document ids in this account.
:param dbx: Dropbox instance with logged in account with sufficient permissions to list documents.
:param page_size: Number of document ids to to get with one request.
:return: Dropbox Paper ids.
"""
listing = dbx.paper_docs_list(limit=page_size)
while True:
for document_id in listing.doc_ids:
yield document_id
if listing.has_more:
listing = dbx.paper_docs_list_continue(listing.cursor.value)
else:
break
def download_resource_file(url: str, fd: io.TextIOWrapper):
""" Download a file.
:param url: The url to get the file from.
:param fd: The file descriptor to write the file to.
"""
response = requests.get(url, stream=True, verify=False)
for chunk in response.iter_content(chunk_size=2 ** 10):
fd.write(chunk)
def replace_images(tracker: Tracker, folders: list, document_reference: str, body: bytes):
""" Find all image references, download them and replace the references to the downloaded copies.
:param tracker: Instance of the tracker to create new files with.
:param folders: List of folder names where the document is stored.
:param document_reference: A string unique to the document.
:param body: The documents body to search in.
:return: The document body with replaced image references.
"""
pattern = re.compile(rb'(<img[^<]+src=)(?P<delimiter>[\'"])(?P<url>[^\'"]+)(?P=delimiter)([^>]*>)')
relative_resource_dir = '.%s' % document_reference
cache = {}
for index, match in enumerate(pattern.finditer(body)):
begin, delimiter, url, end = match.groups()
if url in cache:
body = body.replace(match.group(0), begin + delimiter + cache[url].encode('utf-8') + delimiter + end)
else:
file_name = ("%d_" % index) + urllib.parse.urlparse(url).path.split(b'/')[-1].decode('utf-8')
relative_url = os.path.join(relative_resource_dir, file_name)
body = body.replace(match.group(0), begin + delimiter + relative_url.encode('utf-8') + delimiter + end)
cache[url] = relative_url
with tracker.file_handler(folders + [relative_resource_dir], file_name) as fd:
if fd:
download_resource_file(url.decode('utf-8'), fd)
return body
def store_document(export_format: str, tracker: Tracker, dbx: dropbox.Dropbox, document_id: str):
""" Download a document to the local file system.
:param export_format: The format to store the document in. Possible values are "html", "markdown"
or "all". For "html" also referenced images are downloaded.
:param tracker: Instance of the tracker to create new files with.
:param dbx: Dropbox instance with logged in account with sufficient permissions to download documents.
:param document_id: The document id if the paper document to download.
"""
try:
folders = [folder.name.replace('/', '+')
for folder
in dbx.paper_docs_get_folder_info(document_id).folders or []]
except dropbox.exceptions.ApiError:
folders = []
try:
if export_format == 'html' or export_format == 'all':
document_meta, document_body = dbx.paper_docs_download(document_id, dropbox.paper.ExportFormat('html'))
document_reference = "%s-%s" % (document_id, document_meta.revision)
content = replace_images(tracker, folders, document_reference, document_body.content)
file_name = "%s [%s].html" % (document_meta.title.replace('/', '+'), document_reference)
with tracker.file_handler(folders, file_name) as fd:
if fd:
fd.write(content)
if export_format == 'markdown' or export_format == 'all':
document_meta, document_body = dbx.paper_docs_download(document_id, dropbox.paper.ExportFormat('markdown'))
document_reference = "%s-%s" % (document_id, document_meta.revision)
content = document_body.content
file_name = "%s [%s].md" % (document_meta.title.replace('/', '+'), document_reference)
with tracker.file_handler(folders, file_name) as fd:
if fd:
fd.write(content)
except dropbox.exceptions.ApiError as e:
logging.exception('dropbox api error for document %s: %s', document_id, e)
def backup(token: str, target: str, export_format='all', max_workers=5):
""" Download all accessed documents in the dropbox account.
:param token: Token to login to the dropbox account.
:param target: Relative or absolute path to the download target.
:param export_format: he format to store the document in.
"""
dbx_session = dropbox.dropbox.create_session(max_connections=max_workers * 2)
dbx = dropbox.Dropbox(token, session=dbx_session)
tracker = Tracker(os.path.abspath(target))
pool = Pool(max_workers=max_workers)
for index, document_id in enumerate(paper_documents(dbx)):
pool.submit(store_document, export_format, tracker, dbx, document_id)
pool.shutdown()
tracker.cleanup()
def get_token():
""" Request a new token to acces an dropbox account. """
auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_KEY, obf(APP_SECRET).decode('ascii'))
auth_url = auth_flow.start()
webbrowser.open(auth_url)
print("1. Go to: %s" % auth_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()
# noinspection PyBroadException
try:
oauth_result = auth_flow.finish(auth_code)
except Exception:
logging.exception("Receiving token failed.")
sys.exit(1)
else:
print("Token received. From now on please start this script with:")
print(" --token=%s" % oauth_result.access_token)
return oauth_result.access_token
if __name__ == '__main__':
sys.excepthook = lambda c, e, t: logging.critical('%s: %s\n%s', c, e, ''.join(traceback.format_tb(t)))
arguments = docopt.docopt(__doc__.format(cmd=__file__))
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("dropbox").setLevel(logging.WARNING)
logging.basicConfig(
filename=arguments['--logfile'],
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S%z",
level=logging.DEBUG if arguments['--verbose'] else logging.INFO)
if not arguments['--token']:
arguments['--token'] = get_token()
if arguments['markdown']:
backup(token=arguments['--token'],
target=arguments['<target>'],
export_format='markdown',
max_workers=int(arguments['--workers']))
elif arguments['html']:
backup(token=arguments['--token'],
target=arguments['<target>'],
export_format='html',
max_workers=int(arguments['--workers']))
else:
backup(token=arguments['--token'],
target=arguments['<target>'],
max_workers=int(arguments['--workers']))