/
monitor.py
60 lines (46 loc) · 2.01 KB
/
monitor.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
from watchdog.events import PatternMatchingEventHandler
import os.path as path
import set_queue as queue
import os
import dropbox
import urllib3
import log
class SyncHandler(PatternMatchingEventHandler):
def __init__(self, client, watchDirectory, destDirectory):
super(SyncHandler, self).__init__()
self.client = client
self.watchDirectory = path.normpath(watchDirectory)
self.destDirectory = destDirectory
self.updateQueue = queue.SetQueue()
def update(self):
filesFailed = []
while not self.updateQueue.empty():
# get filename from queue
filename = self.updateQueue.get()
# ensure the pathname for the file is complete
# in order to prevent errors indicating a file doesn't exist
filepath = path.join(self.watchDirectory, os.path.basename(filename))
# update file to the dropbox server
file = open(filepath, "rb")
try:
self.client.put_file(path.join(self.destDirectory, path.basename(filename)), file, overwrite=True)
log.printLog("file updated to dropbox: " + filename)
except (urllib3.exceptions.MaxRetryError, dropbox.rest.ErrorResponse):
log.printLog("failed to upload: " + filename)
# add file to the list of failed files
filesFailed.append(filename)
file.close()
# notify that the current task is done
self.updateQueue.task_done()
if filesFailed:
# readd failed files to the queue
for filename in filesFailed:
self.updateQueue.put(filename)
def on_modified(self, event):
if not event.is_directory:
self.updateQueue.put(event.src_path)
log.printLog("updated the file " + event.src_path)
def on_created(self, event):
if not event.is_directory:
self.updateQueue.put(event.src_path)
log.printLog("added the file " + event.src_path)